m2geval / r /quickr_function_bench.jsonl
Tswatery's picture
Add files using upload-large-folder tool
f18999e verified
Raw
History Blame Contribute Delete
497 kB
{"repo_name": "quickr", "file_name": "/quickr/R/manifest.R", "inference_info": {"prefix_code": "\n\n\n### local variables with unspecified size are 'allocatable'. If they are bound\n### to a named symbol, the manifest must mark it as allocatable.\n###\n### Generally, if an expression produces an array of unspecified size, even if\n### it's never bound, it's still 'allocatable'. For example, an inline fortran\n### `pack()` call likely still produces a corresponding `malloc()` in the\n### generated code, regardless of if the output of `pack()` is bound to\n### a symbol (in the case of pack specifically, the malloc is behind a\n### _gfortran_pack() call.\n###\n### We can potentially link/mask `_malloc` and `_free` with a custom one that\n### uses R_alloc(), which will automatically free after the .External() call\n### returns. We can also pass along -fstack-arrays to gfortran and flang-new\n### (llvm), and that will mostly get rid most of the malloc calls, instead\n### allocating arrays on the C stack (which will automatically free on\n### return/lngjmp), but that will run into issues with larger arrays (especially\n### on windows)\n###\n### local vars of undefined sizes are allocatable. These will typically be\n### allocated on the c stack if they are not too large, but may include a\n### malloc+free call if they are large. Those might leak if we lngjmp\n### away (e.g., due to an interrupt). This potential leak is a non-issue for\n### now, since interrupts aren't supported yet, so there is no risk of lngjmp.\n###\n### When we do add support for interruptable quick functions, this potential\n### leak could be guarded against by:\n###\n### a) linking malloc -> R_alloc() for the fortran compilation unit which\n### would make the memory automatically be released after .External()\n### return. Note that unlinke malloc(), R_alloc() is not thread safe, so we would need\n### additional work for a `do concurrent` context to be supported.\n###\n### b) forcing all arrays to be stack allocated with -fstack-arrays passed\n### to the gfortran/flang-new. This is not a great, since c stack limits are\n### typically \"small\" and enforced by the OS.\n\nr2f.scope <- function(scope) {\n\n vars <- as.list.environment(scope, all.names = TRUE)\n vars <- lapply(vars, ", "suffix_code": ")\n\n # vars that will be visible in the C bridge, either as an input or output\n non_local_var_names <- unique(c(names(formals(scope@closure)),\n closure_return_var_name(scope@closure)))\n\n # collect all size_names; sort so non-locals are declared first.\n size_names <- unique(unlist(lapply(non_local_var_names, function(name) {\n var <- scope[[name]]\n lapply(var@dims, all.names, functions = FALSE, unique = TRUE)\n }))) |> setdiff(names(formals(scope@closure)))\n\n sizes <- lapply(size_names, function(name) {\n kind <- if (endsWith(name, \"_len_\")) \"c_ptrdiff_t\" else \"c_int\"\n glue(\"integer({kind}), intent(in), value :: {name}\")\n })\n\n manifest <- compact(list(\n sizes = sizes,\n args = vars[non_local_var_names],\n locals = vars[setdiff(names(vars), non_local_var_names)]\n ))\n\n manifest <- imap(manifest, \\(declarations, category)\n str_flatten_lines(paste(\"!\", category), declarations)) |>\n str_flatten(\"\\n\\n\")\n\n manifest <- str_flatten_lines(\"! manifest start\", manifest, \"! manifest end\")\n\n # symbols that must come in as args to the subroutine\n # # method=\"radix\" for locale-independent stable order.\n signature <- unique(c(non_local_var_names, sort(size_names, method = \"radix\")))\n attr(manifest, \"signature\") <- signature\n\n manifest\n}\n\n\n\n## fortran precedence order\n## ** (exp)\n## * /\n## + -\n##\n## R prededence order\n## ^\n## - +\n## %/% %%\n## * /\n\n## generally, we just deparse() to convert an axis size.\n## except for NA, which becomes \":\"\n\ndims2f_eval_base_env <- new.env(parent = emptyenv())\ndims2f_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\n\n# any call always evaluates to a string.\n# every argument will be either:\n# - NA -> translates to \":\"\n# - a symbol -> translates to deparsed string\n# - a call ->\n\ndims2f_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2f_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2f_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2f_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"real({e1}) / real({e2})\")\n# dividing integers truncates towards 0\ndims2f_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"int({e1}) / int({e2})\")\ndims2f_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"mod(int({e1}), int({e2}))\")\ndims2f_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1})**({e2})\")\n\n\ndims2f <- function(dims, scope) {\n syms <- unique(unlist(lapply(dims, \\(d) if (is.language(d)) all.vars(d))))\n vars <- as.list(syms)\n names(vars) <- syms\n eval_env <- list2env(vars, parent = dims2f_eval_base_env)\n dims <- map_chr(dims, function(d) {\n d <- eval(d, eval_env)\n if (is.symbol(d)) as.character(d)\n else if (is_wholenumber(d)) as.character(d)\n else if (is_scalar_na(d)) \":\"\n else if (is_string(d)) d\n else if (inherits(d, Variable)) {\n # a locally allocated var that is a return var\n if (!d@modified && d@is_arg)\n return(d@name)\n stop(\"unexpected axis size value\")\n }\n })\n if (!length(dims) || identical(dims, \"1\")) \"\"\n else str_flatten_commas(dims)\n}\n\n", "middle_code": "function(var) {\n intent_in <- var@name %in% names(formals(scope@closure))\n intent_out <- var@name == closure_return_var_name(scope@closure) || intent_in && var@modified\n intent <-\n if (intent_in && intent_out) \"intent(in out)\"\n else if (intent_in) \"intent(in)\"\n else if (intent_out) \"intent(out)\"\n else NULL\n type <- switch(var@mode,\n double = \"real(c_double)\",\n integer = \"integer(c_int)\",\n complex = \"complex(c_double_complex)\",\n logical = if (intent_in || intent_out) \"integer(c_int)\" else \"logical\",\n raw = \"integer(c_int8_t)\",\n stop(\"unrecognized kind: \", format(var))\n )\n dims <- if (passes_as_scalar(var)) {\n NULL\n } else {\n dims2f(var@dims, scope) |> str_flatten_commas() |> sprintf(fmt = \"(%s)\")\n }\n allocatable <- if (!is.null(dims) && grepl(\":\", dims, fixed = TRUE))\n \"allocatable\"\n if (intent_in && intent_out && !is.null(allocatable))\n stop(\"all input and output vars must have a fully defined shape\")\n name <- var@name\n comment <- if (var@mode == \"logical\") \" ! logical\"\n glue('{str_flatten_commas(type, intent, allocatable)} :: {name}{dims}{comment}',\n .null = \"\")\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/quickr/R/c-wrapper.R", "\nmake_c_bridge <- function(fsub, strict = TRUE, headers = TRUE) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n closure <- fsub@closure\n scope <- fsub@scope\n\n fsub_arg_names <- fsub@signature # arg names\n closure_arg_names <- names(formals(closure))\n\n c_body <- character()\n\n if (!all(closure_arg_names %in% fsub_arg_names))\n stop(\"Undeclared arguments: \", str_flatten_commas(setdiff(closure_arg_names, fsub_arg_names)))\n\n closure_arg_vars <- mget(closure_arg_names, scope)\n\n # first unpack all the input vars into named C variables (including sizes and pointer)\n append(c_body) <- lapply(closure_arg_vars, closure_arg_c_defs, strict = strict) |>\n rbind(\"\")\n\n ## TODO, might still need to define a length size for vars where rank>1, if in checks.\n\n # now do all size checks.\n append(c_body) <- lapply(closure_arg_vars, closure_arg_size_checks, scope = scope)\n\n # maybe define and allocate the output var\n n_protected <- 0L\n return_var <- get(closure_return_var_name(closure), scope)\n if (!return_var@name %in% closure_arg_names) {\n return_var@modified <- TRUE\n assign(return_var@name, return_var, scope)\n append(c_body) <- return_var_c_defs(return_var, fsub@scope)\n add(n_protected) <- 1L # allocated return var\n if (return_var@rank > 1)\n add(n_protected) <- 1L # allocated _dim_sexp\n }\n\n fsub_call_args <- fsub_arg_names |>\n lapply(\\(nm) paste0(nm, if (!is_size_name(nm)) \"__\")) |>\n unlist()\n\n if (length(fsub_call_args) > 3)\n fsub_call_args <- paste0(\"\\n \", fsub_call_args)\n\n append(c_body) <- c(\"\", glue(\"{fsub@name}({str_flatten_commas(fsub_call_args)});\"), \"\")\n if (n_protected > 0)\n append(c_body) <- glue(\"UNPROTECT({n_protected});\")\n append(c_body) <- glue(\"return {return_var@name};\")\n\n c_args <- paste(\"SEXP\", names(formals(closure)), collapse = \", \")\n c_body <- as_glue(str_flatten_lines(c_body))\n\n c_func_def <- glue(\"SEXP {fsub@name}_(SEXP _args) {c_block(c_body)}\")\n\n fsub_extern_decl <- fsub_extern_decl(fsub)\n\n c_headers <- glue::trim(r\"--(\n #define R_NO_REMAP\n #include <R.h>\n #include <Rinternals.h>\n\n\n )--\")\n\n as_glue(str_flatten_lines(c(\n if (headers) c_headers,\n fsub_extern_decl, \"\",\n c_func_def)\n ))\n}\n\n\nclosure_arg_c_defs <- function(var, strict = TRUE) {\n\n name <- var@name\n mode <- var@mode\n\n c_code <- character()\n\n name <- var@name\n SEXPTYPE <- sexptype(var@mode)\n protect <- glue(\"SETCAR(_args, {var@name});\")\n\n append(c_code) <- glue(\n \"// {name}\n _args = CDR(_args);\n SEXP {var@name} = CAR(_args);\")\n\n # first maybe duplicate or coerce the SEXP if needed.\n append(c_code) <- glue(\"if (TYPEOF({name}) != {SEXPTYPE}) {{\")\n append(c_code) <- indent(if (strict) {\n glue(r\"(\n Rf_error(\"typeof({name}) must be '{mode}', not '%s'\", R_typeToChar({name}));\n )\")\n } else {\n glue(\"{name} = Rf_coerceVector({name}, {SEXPTYPE});\n {protect}\")\n })\n\n\n if (var@modified) {\n dup <- glue('\n {name} = Rf_duplicate({name});\n {protect}\n ')\n\n if (strict) {\n append(c_code) <- c(\"}\", dup)\n } else {\n append(c_code) <- sprintf(\"} else %s\", dup)\n }\n\n } else {\n append(c_code) <- \"}\"\n }\n\n # define the variable that will be passed to the fsub\n append(c_code) <- glue(\n \"{fsub_arg_var_c_type(var)} {name}__ = {sexpdata(var@mode)}({name});\")\n\n\n if (var@rank == 1) {\n size_name <- get_size_name(var)\n append(c_code) <- glue(\"const R_xlen_t {size_name} = Rf_xlength({var@name});\")\n } else if (var@rank > 1) {\n append(c_code) <- glue(\n 'const int* const {var@name}__dim_ = ({{\n SEXP dim_ = Rf_getAttrib({var@name}, R_DimSymbol);\n if (Rf_length(dim_) != {var@rank}) Rf_error(\n \"{var@name} must be a {var@rank}D-array, but length(dim({var@name})) is %i\",\n (int) Rf_length(dim_));\n INTEGER(dim_);}});'\n )\n append(c_code) <- map_chr(seq_len(var@rank), \\(axis) {\n size_name <- get_size_name(var, axis)\n glue(\"const int {size_name} = {var@name}__dim_[{axis-1}];\")\n })\n } else {\n stop(\"bad rank\")\n }\n\n as_glue(str_flatten_lines(c_code))\n}\n\n\n\nclosure_arg_size_checks <- function(var, scope) {\n imap(var@dims, function(d, axis) {\n # axis is either:\n # - an integer\n # - a symbol of a size_name\n # - a call, consisting of only size_name symbols and basic arithmetic ops.\n size_name <- get_size_name(var, axis)\n\n if (is_scalar_integer(d)) {\n return(glue('\n if ({size_name} != {d})\n Rf_error(\"{friendly_size(var, axis)} must be {d}, not %0.f\",\n (double){size_name});'\n ))\n }\n\n if (is.symbol(d)) {\n if (as.character(d) == size_name) {\n # self-named size_name is expected to be passed along to subroutine\n return()\n } else {\n # it's a constraint for another size\n return(glue('\n if ({d} != {size_name})\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_name(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double){d});'\n ))\n }\n }\n\n if (is.call(d)) {\n size.c <- dims2c(list(d), scope)\n return(glue('{{\n const R_xlen_t expected = {size.c};\n if ({size_name} != expected)\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_expression(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double)expected);\n }}'\n ))\n }\n\n stop(\"bad dim\")\n })\n}\n\n\n\n\nreturn_var_c_defs <- function(var, scope) {\n # allocate the return var.\n name <- var@name\n c_dims <- dims2c(var@dims, scope)\n c_len <- c_dims2c_len(c_dims)\n len_name <- get_size_name(var)\n\n c_code <- c(\n glue(\"const R_xlen_t {len_name} = {c_len};\"),\n glue(switch(\n var@mode,\n double = \"\n SEXP {name} = PROTECT(Rf_allocVector(REALSXP, {len_name}));\n double* {name}__ = REAL({name});\",\n integer = \"\n SEXP {name} = PROTECT(Rf_allocVector(INTSXP, {len_name}));\n int* {name}__ = INTEGER({name});\",\n complex = \"\n SEXP {name} = PROTECT(Rf_allocVector(CPLXSXP, {len_name}));\n Rcomplex* {name}__ = COMPLEX({name});\",\n logical = \"\n SEXP {name} = PROTECT(Rf_allocVector(LGLSXP, {len_name}));\n int* {name}__ = LOGICAL({name});\"\n )))\n\n if (var@rank > 1) {\n append(c_code) <- c_block(\n glue(\"\n const SEXP _dim_sexp = PROTECT(Rf_allocVector(INTSXP, {var@rank}));\n int* const _dim = INTEGER(_dim_sexp);\"\n ),\n imap(c_dims, function(d, i) {\n glue(\"_dim[{i-1}] = {d};\")\n }),\n glue(\"Rf_dimgets({var@name}, _dim_sexp);\")\n )\n }\n\n str_flatten_lines(c_code)\n}\n\n\n\n\ndims2c_eval_base_env <- new.env()\n\n\ndims2c_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\ndims2c_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2c_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2c_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2c_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"((double)({e1}) / (double)({e2}))\")\n# dividing integers truncates towards 0\ndims2c_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} / (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} % (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1}**{e2})\")\n\n\ndims2c <- function(dims, scope) {\n if (!length(dims) || identical(dims, list(1L))) {\n return(list(NULL, \"1\"))\n }\n\n syms <- as.character(unique(unlist(lapply(dims, all.vars))))\n\n syms <- mget(syms, scope, ifnotfound = syms) |>\n lapply(function(var) {\n if (is_size_name(var)) {\n return(as.character(var))\n }\n # resolve a variable from scope (i.e., some other arg var)\n if (!inherits(var, Variable))\n stop(\"could not resolve size: \", var)\n glue(\"Rf_asInteger({var@name})\")\n # Should this be as double?\n # TODO: force this into a named c var, to avoid repeated calls\n })\n\n eval_env <- list2env(syms, parent = dims2c_eval_base_env)\n c_dims <- lapply(dims, function(d) {\n if (inherits(d, Variable))\n return(glue(\"Rf_asInteger({d@name})\"))\n eval(d, eval_env)\n })\n\n c_dims\n}\n\nc_dims2c_len <- function(c_dims) {\n if (length(c_dims) == 1)\n c_dims[[1L]]\n else\n paste0(\"(\", unlist(c_dims), \")\", collapse = \" * \" )\n # eval(Reduce(\\(a, b) { call(\"*\", as.symbol(a@name), as.symbol(b@name)) }, dims),\n # eval_env)\n}\n\n\n# --- utils ----\n\nc_block <- function(...) {\n as_glue(paste0(c(\"{\", indent(c(...)), \"}\"), collapse = \"\\n\"))\n}\n\n# is_var_size <- function(x) inherits(x, VariableSize)\n\npasses_as_scalar <- function(var) {\n var@rank == 0 || var@rank == 1 && identical(var@dims, list(1L))\n}\n\npasses_as_value <- function(var) {\n passes_as_scalar(var) && isFALSE(var@modified)\n}\n\nsexptype <- function(mode) {\n switch(mode,\n integer = \"INTSXP\",\n double = \"REALSXP\",\n complex = \"CPLXSXP\",\n logical = \"LGLSXP\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nsexpdata <- function(mode) {\n switch(mode,\n integer = \"INTEGER\",\n double = \"REAL\",\n complex = \"COMPLEX\",\n logical = \"LOGICAL\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nis_size_name <- function(name) {\n if (is.symbol(name)) {\n name <- as.character(name)\n } else if (!is_string(name)) {\n return(FALSE)\n }\n\n grepl(\"(_len_|_dim_[0-9]+_)$\", name)\n}\n\nfriendly_size <- function(var, axis = NULL) {\n if (is.null(axis) || var@rank == 1 && axis == 1)\n glue(\"length({var@name})\")\n else\n glue(\"dim({var@name})[{axis}]\")\n}\n\nas_friendly_size_name <- function(size_name) {\n size_name <- as.character(size_name)\n if (endsWith(size_name, \"__len_\"))\n sprintf(\"length(%s)\", sub(\"__len_$\", \"\", size_name))\n else\n sub(\"^(.*)__dim_([0-9]+)_$\", \"dim(\\\\1)[\\\\2]\", size_name)\n}\n\nas_friendly_size_expression <- function(d) {\n stopifnot(is.call(d))\n nms <- all.names(d, functions = FALSE, unique = TRUE)\n friendly_substitutions <- new.env(parent = emptyenv())\n for(name in nms)\n if (is_size_name(name))\n assign(name, str2lang(as_friendly_size_name(name)), friendly_substitutions)\n d <- substitute_(d, friendly_substitutions)\n d <- call(\"(\", d)\n deparse1(d)\n}\n\nclosure_return_var_name <- function(closure) {\n return_var_name <- last(body(closure))\n if (!is.symbol(return_var_name))\n stop(\"return value must be a symbol\")\n as.character(return_var_name)\n}\n\n\nfsub_arg_var_c_type <- function(var) {\n type <- switch(var@mode,\n double = \"double*\",\n integer = \"int*\",\n complex = \"Rcomplex*\",\n logical = \"int*\",\n )\n\n # the first const declares that the pointed to values can't be modified\n # (the array values are read only)\n # the second const declares that the pointer itself can't be modified\n # (the fsub can never move/reallocate the array, so this const is always present)\n paste0(c(if (!var@modified) \"const\", type, \"const\"),\n collapse = \" \")\n}\n\nfsub_extern_decl <- function(fsub) {\n fsub_arg_names <- fsub@signature # arg names\n scope <- fsub@scope\n\n fsub_c_sig <- map_chr(fsub_arg_names, function(name) {\n if (is_size_name(name)) {\n type <- if (endsWith(\"__len_\", name))\n \"R_xlen_t\" else \"R_len_t\"\n glue(\"const {type} {name}\")\n } else {\n var <- get(name, fsub@scope)\n glue(\"{fsub_arg_var_c_type(var)} {var@name}__\")\n }\n })\n if (length(fsub_c_sig) >= 3L)\n fsub_c_sig <- paste0(\"\\n \", fsub_c_sig)\n\n glue(\"extern void {fsub@name}({str_flatten_commas(fsub_c_sig)});\")\n}\n"], ["/quickr/R/r2f.R", "\n\n\n# Take parsed R code (anything returnable by base::str2lang()) and returns\n# a Fortran object, which is a string of Fortran code and some attributes\n# describing the value.\nlang2fortran <- r2f <- function(e, scope = NULL, ..., calls = character(), hoist = NULL) {\n ## 'hoist()' is a function that individual handlers can call to pre-emit some\n ## Fortran code. E.g., to setup a temporary variable if the generated Fortran\n ## code doesn't neatly translate into a single expression.\n hoisted <- character()\n if (is.null(hoist)) {\n delayedAssign(\"hoist_connection\", textConnection(\"hoisted\", \"w\", TRUE))\n hoist <- function(...) {\n writeLines(as.character(unlist(c(character(), ...))),\n hoist_connection)\n }\n # if performance with textConnection() becomes an issue, maybe switch to an\n # anonymous file(), though, each hoisting context is typically shortlived and\n # usually 0 lines are hoisted per context, and if they are hoisted, a small number.\n }\n\n fortran <- switch(typeof(e),\n language = {\n # a call\n handler <- get_r2f_handler(callable <- e[[1L]])\n\n match.fun <- attr(handler, \"match.fun\", TRUE)\n if (is.null(match.fun)) {\n match.fun <- get0(callable, parent.env(globalenv()),\n mode = \"function\")\n # this is a best effort to, eg. resolve `seq.default` from `seq`.\n # This should likely be moved into attaching the `match.fun` attr\n # to handlers, for more involved resolution (e.g., with getS3Method())\n if (\"UseMethod\" %in% all.names(body(match.fun)))\n match.fun <- get0(paste0(callable, \".default\"),\n parent.env(globalenv()),\n mode = \"function\",\n ifnotfound = match.fun)\n }\n if (typeof(match.fun) == \"closure\") {\n e <- match.call(match.fun, e)\n }\n\n if (isTRUE(getOption(\"quickr.r2f.debug\"))) {\n\n try(handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)) -> res\n if (inherits(res, \"try-error\")) {\n debugonce(handler)\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n }\n\n res\n\n } else {\n\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n\n }\n\n },\n\n integer = ,\n double = ,\n complex = ,\n logical = atomic2Fortran(e),\n\n symbol = {\n s <- as.character(e)\n # logicals that come in from R are passed as integer types,\n # so for all fortran ops we cast to logical with /=0\n if (\n !is.null(scope[[e]] -> val) &&\n val@mode == \"logical\" &&\n val@is_external\n ) {\n s <- paste0(\"(\", s, \"/=0)\")\n }\n Fortran(s, value = scope[[e]])\n },\n\n ## handling 'object' and 'closure' here are both bad ideas,\n ## TODO: delete both\n # \"object\" = {\n # if (inherits(e, Variable))\n # e <- Fortran(character(), e)\n # stopifnot(inherits(e, Fortran))\n # e\n # },\n\n closure = {\n if (is.null(name <- attr(e, \"name\", TRUE))) {\n name <- if (is.symbol(name <- substitute(e)))\n as.character(name)\n else\n \"anonymous_function\"\n }\n\n stopifnot(is.null(scope))\n new_fortran_subroutine(name, e)\n },\n\n ## all the other typeof() possible values\n # \"character\",\n # \"raw\" ,\n # \"list\",\n # \"NULL\",\n # \"function\",\n # \"special\",\n # \"builtin\",\n # \"environment\",\n # \"S4\",\n # \"pairlist\",\n # \"promise\",\n # \"char\",\n # \"...\",\n # \"any\",\n # \"expression\",\n # \"externalptr\",\n # \"bytecode\",\n # \"weakref\"\n # default\n stop(\"Unsupported object type encountered: \", typeof(e))\n )\n\n if (length(hoisted)) {\n combined <- str_flatten_lines(c(hoisted, fortran))\n attributes(combined) <- attributes(fortran)\n fortran <- combined\n }\n\n attr(fortran, \"r\") <- e\n fortran\n}\n\n\natomic2Fortran <- function(x) {\n stopifnot(is_scalar_atomic(x))\n s <- switch(typeof(x),\n double =,\n integer = num2fortran(x),\n logical = if (x) \".true.\" else \".false.\",\n complex = sprintf(\"(%s, %s)\", num2fortran(Re(x)), num2fortran(Im(x))))\n Fortran(s, Variable(typeof(x)))\n}\n\nnum2fortran <- function(x) {\n stopifnot(typeof(x) %in% c(\"integer\", \"double\"))\n digits <- 7L\n nsmall <- switch(typeof(x), integer = 0L, double = 1L)\n repeat {\n s <- format.default(x, digits = digits, nsmall = nsmall, scientific = 1L)\n if (x == eval(str2lang(s))) # eval() needed for negative and complex numbers\n break\n add(digits) <- 1L\n if (digits > 22L)\n stop(\"number formatting error: \", x, \" formatted as : \", s)\n }\n paste0(s, switch(typeof(x), double = \"_c_double\", integer = \"_c_int\"))\n}\n\n\nr2f_handlers := new.env(parent = emptyenv())\n\nget_r2f_handler <- function(name) {\n stopifnot(\"All functions called must be named as symbols\" = is.symbol(name))\n get0(name, r2f_handlers) %||% stop(\"Unsupported function: \", name, call. = FALSE)\n}\n\nr2f_default_handler <- function(args, scope = NULL, ..., calls) {\n # stopifnot(is.call(e), is.symbol(e[[1L]]))\n\n x <- lapply(args, r2f, scope = scope, calls = calls, ...)\n s <- sprintf(\"%s(%s)\", last(calls), str_flatten_commas(x[-1]))\n Fortran(s)\n}\n\n## ??? export as S7::convert() methods?\nregister_r2f_handler <- function(name, fun) {\n stopifnot(\n is_string(name),\n identical(formals(fun), alist(x = , scope = NULL))\n )\n\n r2f_handlers[[name]] <- fun\n}\n\n.r2f_handler_not_implemented_yet <- function(e, scope, ...) {\n stop(gettextf(\"'%s' is not implemented yet\", as.character(e[[1L]])),\n call. = FALSE)\n}\n\nr2f_handlers[[\"declare\"]] <- function(args, scope, ...) {\n\n for (a in args) {\n if (is_missing(a)) {\n next\n }\n if (is_type_call(a)) {\n var <- type_call_to_var(a)\n var@is_arg <- var@name %in% names(formals(scope@closure))\n scope[[var@name]] <- var\n } else if (is_call(a, quote(`{`))) {\n Recall(as.list(a)[-1], scope)\n }\n }\n\n Fortran(\"\")\n}\n\n\nr2f_handlers[[\"Fortran\"]] <- function(args, scope = NULL, ...) {\n if (!is_string(args[[1]]))\n stop(\"Fortran() must be called with a string\")\n Fortran(args[[1]])\n # enable passing through literal fortran code\n # used like:\n # Fortran(\"nearest(x, 1)\", double(length(x)))\n # Fortran(\"nearest(x, 1)\", x)\n # Fortran(\"x = nearest(x, 1)\")\n}\n\nr2f_handlers[[\"(\"]] <- function(args, scope, ...) {\n r2f(args[[1L]], scope, ...)\n}\n\nr2f_handlers[[\"{\"]] <- function(args, scope, ..., hoist = NULL) {\n # every top level R-expr / fortran statement gets its own hoist target.\n x <- lapply(args, r2f, scope, ...)\n code <- str_flatten_lines(x)\n\n # browser()\n value <- (if (length(args)) last(x)@value) %||% Variable()\n Fortran(code, value)\n}\n\n\n\n# ---- reduction intrinsics ----\n\n\ncreate_mask_hoist <- function() {\n .hoisted_mask <- NULL\n\n try_set <- function(mask) {\n stopifnot(inherits(mask, Fortran), mask@value@mode == \"logical\")\n # each hoist can only accept one mask.\n if (is.null(.hoisted_mask)) {\n .hoisted_mask <<- mask\n return(TRUE)\n }\n # if the mask is identical, we accept it.\n if (identical(.hoisted_mask, mask)) {\n return(TRUE)\n }\n # can't hoist this mask.\n FALSE\n }\n\n get_hoisted <- function() .hoisted_mask\n\n environment()\n}\n\n\nr2f_handlers[[\"max\"]] <-\nr2f_handlers[[\"min\"]] <-\nr2f_handlers[[\"sum\"]] <-\nr2f_handlers[[\"prod\"]] <- function(args, scope, ...) {\n intrinsic <- switch(last(list(...)$calls),\n max = \"maxval\",\n min = \"minval\",\n sum = \"sum\",\n prod = \"product\")\n\n reduce_arg <- function(arg) {\n mask_hoist <- create_mask_hoist()\n x <- r2f(arg, scope, ..., hoist_mask = mask_hoist$try_set)\n if(x@value@rank == 0)\n return(x)\n hoisted_mask <- mask_hoist$get_hoisted()\n s <- glue(\n if (is.null(hoisted_mask))\n \"{intrinsic}({x})\"\n else\n \"{intrinsic}({x}, mask = {hoisted_mask})\"\n )\n Fortran(s, Variable(x@value@mode))\n }\n\n if (length(args) == 1) {\n reduce_arg(args[[1]])\n } else {\n args <- lapply(args, reduce_arg)\n mode <- reduce_promoted_mode(args)\n s <- switch(last(list(...)$calls),\n max = glue(\"max({str_flatten_commas(args)})\"),\n min = glue(\"min({str_flatten_commas(args)})\"),\n sum = glue(\"({str_flatten(args, ' + ')})\"),\n prod = glue(\"({str_flatten(args, ' * ')})\")\n )\n Fortran(s, Variable(mode))\n }\n}\n\n\nr2f_handlers[[\"which.max\"]] <-\nr2f_handlers[[\"which.min\"]] <-\nfunction(args, scope = NULL, ...) {\n stopifnot(length(args) == 1)\n x <- r2f(args[[1L]], scope, ...)\n stopifnot(\"Values passed to which.max()/which.min() must be 1d arrays\" = x@value@rank == 1)\n valout <- Variable(mode = \"integer\") # integer scalar\n\n if (x@value@mode == \"logical\") {\n val <- switch(last(list(...)$calls),\n which.max = \".true.\",\n which.min = \".false.\")\n f <- glue(\"findloc({x}, {val}, 1)\")\n } else {\n intrinsic <- switch(last(list(...)$calls),\n which.max = \"maxloc\",\n which.min = \"minloc\")\n f <- glue(\"{intrinsic}({x}, 1)\")\n }\n\n Fortran(f, valout)\n}\n\n\nr2f_handlers[[\"[\"]] <- function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n\n # only a subset of R's x[...] features can be translated here. `...` can only be:\n # - a single logical mask, of the same rank as `x`. returns a rank 1 vector.\n # - a number of arguments matching the rank of `x`, with each being\n # an integer of rank 0 or 1. In this case, a rank 1 logical becomes\n # converted to an integer with\n\n var <- args[[1]]\n var <- r2f(var, scope, ...)\n\n idxs <- whole_doubles_to_ints(args[-1])\n idxs <- imap(idxs, function(idx, i) {\n if (is_missing(idx))\n Fortran(\":\", Variable(\"integer\", var@value@dims[[i]]))\n else\n r2f(idx, scope, ...)\n })\n\n if (length(idxs) == 1 &&\n idxs[[1]]@value@mode == \"logical\" &&\n idxs[[1]]@value@rank == var@value@rank) {\n mask <- idxs[[1]]\n if (hoist_mask(mask))\n return(var)\n return(Fortran(glue(\"pack({var}, {mask})\"), Variable(var@value@mode, dims = NA)))\n }\n\n if (length(idxs) != var@value@rank)\n stop(\"number of args to x[...] must match the rank of x, received:\",\n deparse1(as.call(c(quote(`[`,args )))))\n\n drop <- args$drop %||% TRUE\n\n idxs <- lapply(idxs, function(subscript) {\n # if (!idx@value@rank %in% 0:1)\n # stop(\"all args to x[...] must have rank 0 or 1\",\n # deparse1(as.call(c(quote(`[`,args )))))\n switch(\n paste0(subscript@value@mode, subscript@value@rank),\n logical0 = {\n Fortran(\":\", Variable(\"integer\", NA))\n },\n logical1 = {\n # we convert to a temp integer vector, doing the equivalent of R's which()\n i <- scope@get_unique_var(\"integer\")\n f <- glue(\"pack([({i}, {i}=1, size({subscript}))], {subscript})\")\n return(Fortran(f, Variable(\"int\", NA)))\n },\n integer0 = {\n if (drop)\n subscript\n else\n Fortran(glue(\"{subscript}:{subscript}\"), Variable(\"int\", 1))\n },\n integer1 = {\n subscript\n },\n # double0 = { },\n # double1 = { },\n stop(\n \"all args to x[...] must be logical or integer of rank 0 or 1\",\n deparse1(as.call(c(quote(`[`, args ))))\n )\n )\n })\n\n dims <- drop_nulls(lapply(idxs, \\(idx) idx@value@dims[[1]]))\n outval <- Variable(var@value@mode, dims)\n Fortran(glue(\"{var}({str_flatten_commas(idxs)})\"), outval)\n\n}\n\n\nr2f_handlers[[\":\"]] <- function(args, scope, ...) {\n # depending on context, this translation can vary.\n\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n args <- whole_doubles_to_ints(args)\n .[start, end] <- lapply(args, r2f, scope, ...)\n step <- glue(\"sign(1, {end}-{start})\")\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{start}:{end}:{step}\"),\n \"for\" = glue(\"{start}, {end}, {step}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {start}, {end}, {step}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\nr2f_handlers[[\"seq\"]] <- function(args, scope, ...) {\n args <- whole_doubles_to_ints(args) # only casts if trunc(dbl) == dbl\n if (!is.null(args$length.out) || !is.null(args$along.with)) {\n stop(\"seq(length.out=, along.with=) not implemented yet\")\n }\n\n\n .[from, to, by] <- lapply(args, r2f, scope, ...)[c(\"from\", \"to\", \"by\")]\n by <- by %||% Fortran(glue(\"sign(1, {to}-{from})\"), Variable(\"integer\"))\n\n # Fortran only supports integer sequences in do and implicit do contexts.\n # to make a double sequence, needs to be in via an implied map() call, like\n # seq(1, 10, .1) -> [(x * 0.1, x = 10, 50)]\n #\n # e.g., i <- scope@get_unique_var(\"integer\")\n # glue(\"[({i} * by, {i} = int(from/by), int(to/by))]\")\n if (from@value@mode != \"integer\" ||\n to@value@mode != \"integer\" ||\n by@value@mode != \"integer\")\n stop(\"non-integer seq()'s not implemented yet.\")\n\n # depending on context, this translation can vary.\n #\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{from}:{to}:{by}\"),\n \"for\" = glue(\"{from}, {to}, {by}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {from}, {to}, {by}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\n\n\nr2f_handlers[[\"ifelse\"]] <- function(args, scope, ...) {\n .[mask, tsource, fsource] <- lapply(args, r2f, scope, ...)\n # (tsource, fsource, mask)\n mode <- tsource@value@mode\n dims <- conform(mask@value, tsource@value, fsource@value)@dims\n Fortran(glue(\"merge({tsource}, {fsource}, {mask})\"),\n Variable(mode, dims))\n}\n\n\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- pure elemental unary math intrinsics ----\n\n## real and complex intrinsics\nr2f_handlers[[\"sin\"]] <-\nr2f_handlers[[\"cos\"]] <-\nr2f_handlers[[\"tan\"]] <-\nr2f_handlers[[\"asin\"]] <-\nr2f_handlers[[\"acos\"]] <-\nr2f_handlers[[\"atan\"]] <-\nr2f_handlers[[\"sqrt\"]] <-\nr2f_handlers[[\"exp\"]] <-\nr2f_handlers[[\"log\"]] <-\nr2f_handlers[[\"floor\"]] <-\nr2f_handlers[[\"ceiling\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n intrinsic <- last(list(...)$calls)\n Fortran(glue(\"{intrinsic}({arg})\"), arg@value)\n}\n\nr2f_handlers[[\"log10\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n f <- if(arg@value@mode == \"complex\") {\n glue(\"(log({arg}) / log(10.0_c_double))\")\n } else {\n glue(\"log10({arg})\")\n }\n Fortran(f, arg@value)\n}\n\n## accepts real, integer, or complex\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n if(arg@value@mode == \"complex\")\n arg@value@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- complex elemental unary intrinsics ----\n\nr2f_handlers[[\"Re\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"real({arg})\"), val)\n}\n\nr2f_handlers[[\"Im\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"aimag({arg})\"), val)\n}\n\n# Modulus (magnitude)\nr2f_handlers[[\"Mod\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), val)\n}\n\n# Argument (phase angle, radians)\nr2f_handlers[[\"Arg\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"atan2(aimag({arg}), real({arg}))\"), val)\n}\n\n# conjg() returns a complex value; R uses Conj()\nr2f_handlers[[\"Conj\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"complex\"\n Fortran(glue(\"conjg({arg})\"), val)\n}\n\n\n\n# ---- elemental binary infix operators ----\n\nr2f_handlers[[\"+\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} + {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"-\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} - {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"*\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} * {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"/\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} / {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"^\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} ** {right})\"), conform(left@value, right@value))\n}\n\n\nr2f_handlers[[\">=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} >= {right})\"), var)\n}\nr2f_handlers[[\">\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} > {right})\"), var)\n}\nr2f_handlers[[\"<\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} < {right})\"), var)\n}\nr2f_handlers[[\"<=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} <= {right})\"), var)\n}\nr2f_handlers[[\"==\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} == {right})\"), var)\n}\nr2f_handlers[[\"!=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} /= {right})\"), var)\n}\n\n\n\n# ---- remainder (%%) and integer division (%/%) ----\n#\n# R semantics:\n# x %% y == r where r has the sign of y (divisor)\n# x %/% y == q where q = floor(x / y)\n# and x == r + y * q (within rounding error)\n#\n# Fortran intrinsics:\n# - MODULO(a,p) : remainder with sign(p)\n# - FLOOR(x) : greatest integer ≤ x (real)\n# - AINT(x) : truncation toward 0 (real)\n\nr2f_handlers[[\"%%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n # MODULO gives result with sign(right) – matches R %% behaviour\n Fortran(glue(\"modulo({left}, {right})\"), out_val)\n}\n\nr2f_handlers[[\"%/%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n\n expr <- switch(\n out_val@mode,\n integer = glue(\"int(floor(real({left}) / real({right})))\"),\n double = glue(\"floor({left} / {right})\"),\n stop(\"%/% only implemented for numeric types\")\n )\n\n Fortran(expr, out_val)\n}\n\n\n\n# TODO: the scalar || probably need some more type checking.\n# TODO: gfortran supports implicit casting that of logical to integer when\n# assigning a logical to a variable declared integer, converting `.true.` to `1`,\n# but this is not a standard language feature, and Intel's `ifort` uses `-1` for `.true`.\n# We should explicitly use\n# `merge(1_c_int, 0_c_int, <lgl>)` to cast logical to int.\nr2f_handlers[[\"&\"]] <-\nr2f_handlers[[\"&&\"]] <-\nr2f_handlers[[\"|\"]] <-\nr2f_handlers[[\"||\"]] <-\nfunction(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n args <- lapply(args, function(a) {\n if (a@value@mode != \"logical\") {\n stop(\"must be logical\")\n }\n a\n })\n .[left, right] <- args\n\n operator <- switch(last(list(...)$calls),\n `&` = , `&&` = \".and.\",\n `|` = , `||` = \".or.\")\n\n s <- glue(\"{left} {operator} {right}\")\n val <- conform(left@value, right@value)\n val@mode <- \"logical\"\n Fortran(s, val)\n}\n\n\n\n\n# --- constructors ----\n\n\nr2f_handlers[[\"c\"]] <- function(args, scope = NULL, ...) {\n ff <- lapply(args, r2f, scope, ...)\n s <- glue(\"[ {str_flatten_commas(ff)} ]\")\n lens <- lapply(ff[order(map_int(ff, \\(f) f@value@rank))], function(e) {\n rank <- e@value@rank\n if (rank == 0)\n 1L\n else if (rank == 1)\n e@value@dims[[1]]\n else\n stop(\"all args passed to c() must be scalars or 1-d arrays\")\n })\n mode <- reduce_promoted_mode(ff)\n len <- Reduce(\\(l1, l2) {\n if (is_scalar_na(l1) || is_scalar_na(l2)) {\n NA\n } else if (is_wholenumber(l1) && is_wholenumber(l2)) {\n l1 + l2\n } else {\n call(\"+\", l1, l2)\n }\n }, lens)\n Fortran(s, Variable(mode, list(len)))\n}\n\n\nr2f_handlers[[\"cbind\"]] <- function(e, scope) {\n .NotYetImplemented()\n ee <- lapply(e[-1], r2f, scope)\n ncols <- lapply(ee, function(f) {\n if (f@value@rank %in% c(0, 1))\n 1\n else if (f@value@rank == 2)\n f@value@dims[[2]]\n })\n ncols <- Reduce(\\(a, b) call(\"+\", a, b), ncols)\n ncols <- eval(ncols, scope@sizes)\n}\n\n\n\nr2f_handlers[[\"<-\"]] <- function(args, scope, ...) {\n target <- args[[1]]\n if (is.call(target)) {\n # given a call like `foo(x) <- y`, dispatch to `foo<-`\n target_callable <- target[[1]]\n stopifnot(is.symbol(target_callable))\n name <- as.symbol(paste0(as.character(target_callable), \"<-\"))\n handler <- get_r2f_handler(name)\n return(handler(args, scope, ...)) # new hoist target\n }\n\n # It sure seems like it's be nice if the Fortran() constructor\n # took mode and dims as args directly,\n # without needing to go through Variable...\n stopifnot(is.symbol(target))\n name <- as.character(target)\n\n value <- args[[2]]\n value <- r2f(value, scope, ...)\n\n # immutable / copy-on-modify usage of Variable()\n if (is.null(var <- get0(name, scope))) {\n # this is a binding to a new symbol\n var <- value@value\n var@name <- name\n scope[[name]] <- var\n\n } else {\n # The var already exists, this assignment is a modification / reassignment\n check_assignment_compatible(var, value@value)\n var@modified <- TRUE\n # could probably drop this @modified property, and instead track\n # if the var populated by declare is identical at the end (e.g., perhaps by\n # address, or by attaching a unique id to each var, or ???)\n assign(name, var, scope)\n }\n\n Fortran(glue(\"{name} = {value}\"))\n}\n\n\nr2f_handlers[[\"[<-\"]] <- function(args, scope = NULL, ...) {\n\n # TODO: handle logical subsetting here, which must become a where a construct like:\n # x[lgl] <- val\n # becomes\n # where (lgl)\n # x = val\n # end where\n # ! but if {va} references {x}, it will only see the subset x, not the full {x}\n # e.g.,\n # sum(x) is not the same as `where lgl \\n sum(x) \\n end where`\n # ditto for ifelse() ?\n # e <- as.list(e)\n\n stopifnot(is_call(target <- args[[1L]], \"[\"))\n target <- r2f(target, scope)\n\n value <- r2f(args[[2L]], scope)\n Fortran(glue(\"{target} = {value}\"))\n}\n\nreduce_promoted_mode <- function(...) {\n\n getmode <- function(d) {\n if (inherits(d, Fortran))\n d <- d@value\n if (inherits(d, Variable))\n return(d@mode)\n if (is.list(d) && length(d))\n lapply(d, getmode)\n }\n modes <- unique(unlist(getmode(list(...))))\n\n if (\"double\" %in% modes)\n \"double\"\n else if (\"integer\" %in% modes)\n \"integer\"\n else if (\"logical\" %in% modes)\n \"logical\"\n else\n NULL\n\n}\n\n\nr2f_handlers[[\"=\"]] <- r2f_handlers[[\"<-\"]]\n\nr2f_handlers[[\"logical\"]] <- function(args, scope, ...) {\n Fortran(\".false.\", Variable(mode = \"logical\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"integer\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"integer\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"double\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"double\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"numeric\"]] <- r2f_handlers[[\"double\"]]\n\nr2f_handlers[[\"character\"]] <- r2f_handlers[[\"raw\"]] <-\n .r2f_handler_not_implemented_yet\n\n\nr2f_handlers[[\"matrix\"]] <- function(args, scope = NULL, ...) {\n\n args$data %||% stop(\"matrix(data=) must be provided, cannot be NA\")\n out <- r2f(args$data, scope, ...)\n out@value@dims <- r2dims(list(args$nrow, args$ncol), scope)\n out\n\n # TODO: reshape() if !passes_as_scalar(out)\n}\n\n\n\nconform <- function(..., mode = NULL) {\n var <- NULL\n # technically, types are implicit promoted, but we'll let <- handle that.\n for (var in drop_nulls(list(...))) {\n if (passes_as_scalar(var)) {\n next\n } else {\n break\n }\n }\n if (is.null(var))\n NULL\n else\n Variable(mode %||% var@mode, var@dims)\n }\n\n\n\n# ---- printers ----\n\n\nr2f_handlers[[\"cat\"]] <- function(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n # can do a lot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"character\")\n label <- args[[1]]\n if (!endsWith(label, \"\\n\"))\n stop(\"cat(<strings>) must end with '\\n'\")\n label <- substring(label, 1, nchar(label)-1)\n\n Fortran(glue('call labelpr(\"{label}\", {nchar(label)})'))\n}\n\nr2f_handlers[[\"print\"]] <- function(args, scope = NULL, ...) {\n # args <- lapply(as.list(e)[-1], r2f, scope)\n # args <- as.list(e)[-1]\n # can do alot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"symbol\")\n name <- args[[1]]\n var <- get(name, envir = scope)\n name <- as.character(name)\n if (var@mode == \"logical\")\n name <- sprintf(\"(%s/=0)\", name)\n label <- \"\"\n # browser()\n if (passes_as_scalar(var)) {\n # } \"scalar\"\n # paste0(c(var@mode, scalar) collapse = \"_\"),\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr1\",\n double = \"dblepr1\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name})'))\n } else {\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr\",\n double = \"dblepr\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name}, size({name}))'))\n }\n}\n\n# r2f_handlers[[\"ifelse\"]] <- function(e, scope) {\n# # TODO:\n# # <- and [<- need to be aware of this construct for it to make sense.\n# .[test, yes, no] <- lapply(e[-1], r2f, scope)\n# Fortran(glue(\"where ({test}}\n# {indent(yes)}\n# elsewhere\n# {indent({no})\n# end where\"))\n# }\n\n\nr2f_handlers[[\"length\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x})\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"nrow\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 1)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"ncol\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 2)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"dim\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"shape({x})\"), Variable(\"integer\", x@value@rank))\n}\n\n\n\n\n# this is just `[` handler\nr2f_slice <- function(args, scope, ...) { }\n\n\n\n# ---- control flow ----\n\n\nr2f_handlers[[\"if\"]] <- function(args, scope, ..., hoist = NULL) {\n # cond uses the current hoist context.\n cond <- r2f(args[[1]], scope, ..., hoist = hoist)\n\n # true and false branchs gets their own hoist target.\n true <- r2f(args[[2]], scope, ..., hoist = NULL)\n\n if (length(args) == 2) {\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n end if\n \"))\n } else {\n false <- r2f(args[[3]], scope, ..., hoist = NULL)\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n else\n {indent(false)}\n end if\n \"))\n }\n}\n\n\n# TODO: return\n\n# ---- repeat ----\nr2f_handlers[[\"repeat\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n body <- r2f(args[[1]], scope, ...)\n Fortran(glue(\n \"do\n {indent(body)}\n end do\n \"))\n}\n\n# ---- break ----\nr2f_handlers[[\"break\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"exit\")\n}\n\n# ---- break ----\nr2f_handlers[[\"next\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"cycle\")\n}\n\n# ---- while ----\nr2f_handlers[[\"while\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 2L)\n cond <- r2f(args[[1]], scope, ...)\n body <- r2f(args[[2]], scope, ...) ## should we set a new hoist target here?\n Fortran(glue(\n \"do while ({cond})\n {indent(body)}\n end do\n \"))\n}\n\n## ---- for ----\nr2f_iterable <- function(e, scope, ...) {\n .NotYetImplemented()\n\n if (is.symbol(e)) {\n var <- get(e, scope)\n iterable <- r2f(...)\n }\n\n # list(var, iterable, body_prefix)\n}\n\n\n\n\nr2f_handlers[[\"for\"]] <- function(args, scope, ...) {\n .[var, iterable, body] <- args\n stopifnot(is.symbol(var))\n var <- as.character(var)\n scope[[var]] <- Variable(mode = \"integer\", name = var)\n\n iterable <- r2f_iterable_handlers[[as.character(iterable[[1]])]](iterable, scope)\n body <- r2f(body, scope, ...)\n\n Fortran(glue(\n \"do {var} = {iterable}\n {indent(body)}\n end do\n \"))\n}\n\nr2f_iterable_handlers := new.env()\n\nr2f_iterable_handlers[[\"seq_len\"]] <- function(e, scope, ...) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_len()\")\n x <- x[[1]]\n start <- 1L\n end <- r2f(x)\n glue(\"{start}, {end}\")\n}\n\nr2f_iterable_handlers[[\"seq\"]] <- function(e, scope) {\n\n ee <- match.call(seq.default, e)\n ee <- whole_doubles_to_ints(ee)\n\n start <- r2f(ee$from, scope)\n end <- r2f(ee$to, scope)\n step <- if (is.null(ee$by))\n glue(\"sign(1, {end}-{start})\")\n else\n r2f(ee$by, scope)\n\n str_flatten_commas(\n start, end, step\n )\n}\n\nr2f_iterable_handlers[[\":\"]] <- function(e, scope) {\n\n ee <- whole_doubles_to_ints(e)\n .[start, end] <- as.list(ee)[-1] |> lapply(r2f, scope)\n\n glue(\"{start}, {end}, sign(1, {end}-{start})\")\n}\n\n\n\nr2f_iterable_handlers[[\"seq_along\"]] <- function(e, scope) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_along()\")\n x <- x[[1]]\n start <- 1\n end <- sprintf(\"size(%s)\", r2f(x, scope))\n glue(\"{start}, {end}\")\n}\n\n\n# ---- helpers ----\n\ncheck_call <- function(e, nargs) {\n if (length(e) != (nargs+1L))\n stop(\"Too many args to: \", as.character(e[[1L]]))\n}\n"], ["/quickr/R/subroutine.R", "\n\nnew_fortran_subroutine <- function(name, closure, parent = emptyenv()) {\n\n\n check_all_var_names_valid(closure)\n\n # translate body, and populate scope with variables\n body <- body(closure)\n\n # defuse calls like `-1` and `1+1i`. Not really necessary, but simplifies downstream a little.\n body <- defuse_numeric_literals(body)\n\n # TODO: try harder here to use one of the input vars as the output var\n body <- ensure_last_expr_sym(body)\n\n # update closure with sym return value\n base::body(closure) <- body\n # body <- rlang::zap_srcref(body)\n\n scope <- new_scope(closure, parent)\n\n # inject symbols for var sizes in declare calls, so like:\n # declare(type(foo = integer(nr, NA)),\n # type(bar = integer(nr, 3)))\n # become:\n # declare(type(foo = integer(foo_dim_1_, foo_dim_2_)),\n # type(bar = integer(foo_dim_1_, 3L)))\n body <- substitute_declared_sizes(body)\n body <- r2f(drop_last(body), scope)\n\n # check all input vars were declared\n # TODO: this check might be too late, because r2f() might throw cryptic errors\n # when handling undeclared variables. Either throw better errors from r2f(), or\n # handle all declares first\n for(arg_name in names(formals(closure))) {\n if (is.null(var <- get0(arg_name, scope)))\n stop(\"arg not declared: \", arg_name)\n }\n\n # figure out the return variable.\n if (is.symbol(last_expr <- last(body(closure)))) {\n return_var <- get(last_expr, scope)\n return_var@is_return <- TRUE\n scope[[as.character(last_expr)]] <- return_var\n } else {\n # lots we can still do here, just not implemented yet.\n stop(\"last expression in the function must be a bare symbol\")\n }\n\n manifest <- r2f.scope(scope)\n fsub_arg_names <- attr(manifest, \"signature\", TRUE)\n\n used_iso_bindings <- unique(unlist(use.names = FALSE, list(\n lapply(scope, function(var) {\n list(\n switch(\n var@mode,\n double = \"c_double\",\n integer = \"c_int\",\n logical = if (var@name %in% fsub_arg_names)\n \"c_int\",\n complex = \"c_double_complex\",\n raw = \"c_int8_t\"\n ),\n lapply(var@dims, function(size) {\n syms <- all.vars(size)\n c(if (any(grepl(\"__len_$\", syms))) \"c_ptrdiff_t\",\n if (any(grepl(\"__dim_[0-9]+_$\", syms))) \"c_int\")\n })\n )\n }))))\n\n # check for literal kinds\n if (!\"c_int\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+_c_int\\\\b\", body))\n append(used_iso_bindings) <- \"c_int\"\n }\n if (!\"c_double\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+\\\\.[0-9]+_c_double\\\\b\", body))\n append(used_iso_bindings) <- \"c_double\"\n }\n used_iso_bindings <- sort(used_iso_bindings, method = \"radix\")\n\n subroutine <- glue(\"\n subroutine {name}({str_flatten_commas(fsub_arg_names)}) bind(c)\n use iso_c_binding, only: {str_flatten_commas(used_iso_bindings)}\n implicit none\n\n {indent(manifest)}\n\n {indent(body)}\n end subroutine\n \")\n\n subroutine <- insert_fortran_line_continuations(subroutine)\n\n FortranSubroutine(\n subroutine,\n name = name,\n signature = fsub_arg_names,\n scope = scope,\n closure = closure\n )\n}\n\ninsert_fortran_line_continuations <- function(code, preserve_attributes = TRUE) {\n attrs_in <- attributes(code)\n\n code <- as.character(code)\n lines <- str_split_lines(code)\n lines <- trimws(lines, \"right\")\n\n if (any(too_long <- nchar(lines) > 132)) {\n # remove leading indentation\n lines[too_long] <- trimws(lines[too_long], \"left\")\n\n # move trailing comment at the end\n lines[too_long] <- sub(\"^(.*)!(.*)$\", \"!\\\\2\\n\\\\1\", lines[too_long])\n lines <- str_split_lines(lines)\n\n # maximum 255 continuations are allowed\n for (i in 1:256) {\n if (!any(too_long <- nchar(lines) > 132))\n break\n lines[too_long] <- sub(\"^(.{1,130})\\\\s\", \"\\\\1 &\\n\", lines[too_long])\n lines <- str_split_lines(lines)\n }\n if (i > 255L)\n stop(\"Too long line encountered. Please split long expressions into a sequence of smaller expressions.\")\n }\n\n code <- str_flatten_lines(lines)\n if (preserve_attributes)\n attributes(code) <- attrs_in\n code\n}\n\n"], ["/quickr/R/sizes.R", "\n\n\ncheck_type_call <- function(cl) {\n if (length(cl) > 2)\n stop(\"only one variable can be declared per type() call\")\n args <- as.list(cl)[-1]\n if (length(names(args)) != 1)\n stop(\"name must be provided as: type(<name> = <mode>(<<dims>>)\")\n if (!is.call(args[[1]]) && as.character(args[[1]]) %in% .atomic_type_names)\n stop(\"only atomic modes are supported\")\n}\n\n\ntype_call_to_var <- function(cl) {\n check_type_call(cl)\n Variable(\n name = names(cl)[-1],\n mode = as.character(cl[[2L]][[1L]]),\n dims = unname(as.list(cl[[2]])[-1])\n )\n}\n\nvar_to_type_call <- function(var) {\n arg <- as.call(c(as.symbol(var@mode), var@dims))\n arg <- setNames(list(arg), var@name)\n as.call(c(quote(type), arg))\n}\n\n\nget_flattened_args <- function(cl) {\n # flatten exprs from `{` in usage like declare({ ... })`\n args <- as.list(cl)[-1]\n args <- lapply(args, function(e) {\n if (is_missing(e))\n NULL\n else if (is_call(e, quote(`{`)))\n get_flattened_args(e)\n else\n list(e)\n })\n unlist(args, recursive = FALSE)\n}\n\nself_evaluate <- function(...) sys.call()\n\nsubstitute_declared_sizes <- function(e) {\n stopifnot(is_call(e, quote(`{`)))\n\n aliases <- new.env(parent = emptyenv())\n eval_env <- new.env(parent = emptyenv())\n for(name in all.names(e, functions = TRUE, unique = TRUE))\n assign(name, self_evaluate, eval_env)\n eval_env <- new.env(parent = eval_env)\n for(name in all.names(e, functions = FALSE, unique = TRUE))\n assign(name, as.symbol(name), eval_env)\n\n eval_env$`{` <- function(...) {\n as.call(c(list(quote(`{`)), list(...)))\n }\n\n eval_env$declare <- function(...) {\n args <- get_flattened_args(sys.call())\n args <- lapply(args, function(e) {\n if (is_type_call(e)) {\n var <- type_call_to_var(e)\n var@dims <- imap(var@dims, function(size, axis) {\n size_name <- as.symbol(get_size_name(var, axis))\n if (is.symbol(size) && !exists(size, aliases)) {\n # user defined implicit size_name alias\n assign(as.character(size), size_name, aliases)\n size <- size_name\n } else if (is_scalar_na(size)) {\n size <- size_name\n } else if (is_wholenumber(size)) {\n size <- as.integer(size)\n }\n size\n })\n e <- var_to_type_call(var)\n }\n e\n })\n\n as.call(c(quote(declare), args))\n }\n\n e <- eval(e, eval_env)\n\n # Now the 'aliases' env is populated; go through and substitute\n # size aliases with the actual size name.\n eval_env$declare <- function(...) {\n as.call(lapply(sys.call(), function(e) {\n if (is_type_call(e))\n e <- substitute_(e, aliases)\n e\n }))\n }\n\n eval(e, eval_env)\n\n}\n\n\nr2size <- function(r, scope) {\n typeof(r) |> switch(\n integer = r,\n double = {\n if (is_wholenumber(r))\n as.integer(r)\n else\n stop(\"size must be an integer, found: \", r)\n },\n symbol = {\n if (is_size_name(r))\n return(r)\n var <- get(r, scope)\n if (var@mode != \"integer\" || !passes_as_scalar(var))\n warning(\"size is not an integer:\", as.character(r))\n if (var@is_arg && !var@modified)\n return(r)\n # TODO: add specific unit tests here\n if (identical(var@r, r))\n return(r)\n # make a best effort to use the r expression last assigned to the\n # symbol, or fail gracefully and return NA.\n # closure-locals with unspecified shape are declared allocatable\n # input and/or output args with unspecified shape signal an error.\n r2size(var@r, scope)\n },\n language = {\n as.character(r[[1]]) |> switch(\n `+` = , `-` = , `/` = , `*` = , `^` = , `%/%` = , `%%` = {\n args <- as.list(r)[-1]\n args <- lapply(args, r2size, scope)\n if (anyNA(rapply(args, as.list)))\n return(NA_integer_)\n cl <- as.call(c(r[[1]], args))\n if (all(map_lgl(args, is.atomic)))\n cl <- eval(cl, baseenv())\n cl\n },\n length = {\n var <- get(r[[2L]], scope)\n if (var@rank == 1)\n return(var@dims[[1L]])\n len <- reduce(var@dims, \\(d1, d2) call(\"*\", d1, d2))\n r2size(len, scope)\n },\n `[` = {\n # [ only works when paired with dim()\n if (!is_call(r[[2L]], quote(dim)))\n return(NA_integer_)\n var <- get(r[[2L]][[2L]], scope)\n axis <- r[[3]]\n if (!is_wholenumber(axis))\n return(NA_integer_)\n if (axis > var@rank)\n stop(\"insufficient rank of variable in \", deparse1(r))\n var@dims[[axis]]\n },\n # dim = {\n #\n # },\n nrow = {\n var <- get(r[[2L]], scope)\n var@dims[[1]]\n },\n ncol = {\n var <- get(r[[2L]], scope)\n var@dims[[2]]\n },\n NA_integer_)\n },\n NA_integer_\n )\n}\n\nr2dims <- function(r, scope) {\n if (is.call(r)) {\n as.character(r[[1]]) |> switch(\n dim = {\n var <- get(r[[2L]], scope)\n return(var@dims)\n },\n c = {\n args <- lapply(r[-1], r2dims, scope)\n dims <- unlist(args, recursive = FALSE)\n return(as.list(dims))\n },\n r <- list(r))\n }\n lapply(r, r2size, scope)\n}\n\nget_size_name <- function(var, axis = NULL, name = var@name, rank = var@rank) {\n stopifnot(is.null(axis) || is_wholenumber(axis) && axis > 0)\n if (is.null(axis) || rank == 1 && axis == 1)\n sprintf(\"%s__len_\", name)\n else {\n if (axis > rank) stop(\"axis must not be > rank\")\n sprintf(\"%s__dim_%i_\", name, axis)\n }\n}\n\n\n\n# TODO: allow syntax like:\n# declare(type(a, b, c = integer(1)))\n# or:\n# declare(type(a = , b = , c = integer(1)))\n"], ["/quickr/R/quick.R", "#' Compile a Quick Function\n#'\n#' Compile an R function.\n#'\n#' @param fun An R function\n#' @param name Optional string, name to use for the function.\n#'\n#' @details\n#'\n#' ## `declare(type())` syntax:\n#'\n#' The shape and mode of all function arguments must be declared. Local and\n#' return variables may optionally also be declared.\n#'\n#' `declare(type())` also has support for declaring size constraints, or size\n#' relationships between variables. Here are some examples of declare calls:\n#'\n#' ```r\n#' declare(type(x = double(NA))) # x is a 1-d double vector of any length\n#' declare(type(x = double(10))) # x is a 1-d double vector of length 10\n#' declare(type(x = double(1))) # x is a scalar double\n#'\n#' declare(type(x = integer(2, 3))) # x is a 2-d integer matrix with dim (2, 3)\n#' declare(type(x = integer(NA, 3))) # x is a 2-d integer matrix with dim (<any>, 3)\n#'\n#' # x is a 4-d logical matrix with dim (<any>, 24, 24, 3)\n#' declare(type(x = logical(NA, 24, 24, 3)))\n#'\n#' # x and y are 1-d double vectors of any length\n#' declare(type(x = double(NA)),\n#' type(y = double(NA)))\n#'\n#' # x and y are 1-d double vectors of the same length\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' # x and y are 1-d double vectors, where length(y) == length(x) + 2\n#' declare(type(x = double(n)),\n#' type(y = double(n+2)))\n#' ```\n#'\n#' You can provide declarations to `declare()` as:\n#'\n#' - Multiple arguments to a single `declare()` call\n#' - Separate `declare()` calls\n#' - Multiple arguments within a code block (`{}`) inside `declare()`\n#'\n#' ```r\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' declare(type(x = double(n)))\n#' declare(type(y = double(n)))\n#'\n#' declare({\n#' type(x = double(n))\n#' type(y = double(n))\n#' })\n#' ```\n#'\n#' ## Return values\n#'\n#' The shape and type of a function return value must be known at compile time.\n#' In most situations, this will be automatically inferred by `quick()`. However,\n#' if the output is dynamic, then you may need to provide a hint.\n#' For example, returning the result of `seq()` will fail because the output shape\n#' cannot be inferred.\n#'\n#' ```r\n#' # Will fail to compile:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' ```\n#'\n#' However, if the output size can be declared as a dynamic expression using other\n#' values known at runtime, compilation will succeed:\n#'\n#' ```r\n#' # Succeeds:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' type(out = integer(end - start + 1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' quick_seq(1L, 5L)\n#' ```\n#'\n#' @returns A quicker R function.\n#' @export\n#' @examples\n#' add_ab <- quick(function(a, b) {\n#' declare(type(a = double(n)),\n#' type(b = double(n)))\n#' out <- a + b\n#' out\n#' })\n#' add_ab(1, 2)\nquick <- function(fun, name = NULL) {\n if (is.null(name)) {\n name <- if (is.symbol(substitute(fun)))\n deparse(substitute(fun))\n else\n make_unique_name(prefix = \"anonymous_quick_function_\")\n }\n\n if (nzchar(pkgname <- Sys.getenv(\"DEVTOOLS_LOAD\"))) {\n if (!collector$is_active()) {\n if (!requireNamespace(\"pkgload\", quietly = TRUE)) {\n stop(\"Please install 'pkgload'\")\n }\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_code)) {\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n defer(dump_collected(), sys.frame(i), after = TRUE)\n break\n }\n }\n }\n }\n\n if (collector$is_active()) {\n # we are in a quickr::compile_package() or a devtools::load_all() call,\n # merely collecting functions at this point.\n quick_closure <- create_quick_closure(name, fun)\n collector$add(name = name, closure = fun, quick_closure = quick_closure)\n return(quick_closure)\n }\n\n pkgname <- parent.pkg()\n if (!is.null(pkgname) && pkgname != \"quickr\") {\n # we are in a package - but outside a quickr::compile_package() call.\n return(create_quick_closure(name, fun))\n }\n\n # not in a package. Compile and load eagerly.\n attr(fun, \"name\") <- name\n fun <- compile(r2f(fun))\n attr(fun, \"name\") <- NULL\n\n fun\n}\n\ncompile <- function(fsub, build_dir = tempfile(paste0(fsub@name, \"-build-\"))) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n name <- fsub@name\n c_wrapper <- make_c_bridge(fsub)\n\n if (dir.exists(build_dir)) unlink(build_dir, recursive = T)\n if (!dir.exists(build_dir))\n dir.create(build_dir)\n owd <- setwd(build_dir)\n on.exit(setwd(owd))\n\n fsub_path <- paste0(name, \"_fsub.f90\")\n c_wrapper_path <- paste0(name, \"_c_wrapper.c\")\n dll_path <- paste0(name, .Platform$dynlib.ext)\n writeLines(fsub, fsub_path)\n writeLines(c_wrapper, c_wrapper_path)\n\n suppressWarnings({\n result <- system2(\n R.home(\"bin/R\"),\n c(\"CMD SHLIB --use-LTO\", \"-o\", dll_path, fsub_path, c_wrapper_path),\n stdout = TRUE, stderr = TRUE\n )\n })\n if (!is.null(attr(result, \"status\"))) {\n writeLines(result, stderr())\n str(attributes(result))\n stop(\"Compilation Error\")\n }\n\n # tryCatch(dyn.unload(dll_path), error = identity)\n dll <- dyn.load(dll_path)\n c_wrapper_name <- paste0(fsub@name, \"_\")\n ptr <- getNativeSymbolInfo(c_wrapper_name, dll)$address\n\n create_quick_closure(fsub@name, fsub@closure, native_symbol = ptr)\n}\n\n\n\ncreate_quick_closure <- function(name, closure,\n native_symbol = as.name(paste0(name, \"_\"))) {\n body(closure) <- as.call(c(quote(.External), native_symbol,\n lapply(names(formals(closure)), as.name)))\n closure\n}\n\n\n\ncheck_all_var_names_valid <- function(fun) {\n nms <- unique(c(names(formals(fun)), all.vars(body(fun), functions = FALSE)))\n invalid <- endsWith(nms, \"_\") | startsWith(nms, \"_\") | nms %in% c(\n\n # clashes with Fortran subroutine symbols\n \"c_int\", \"c_double\", \"c_ptrdiff_t\",\n\n # clashes with C bridge symbols\n \"int\" #, \"double\",\n\n # ??? (clashes with R symbols?)\n # \"double\", \"integer\"\n )\n if (any(invalid)) {\n stop(\"symbols cannot start or end with '_', but found: \",\n glue_collapse(invalid, \", \", last = \", and \"))\n }\n}\n\n\n\n# ---- utils ----\n\nmake_unique_name <- local({\n i <- 0L\n function(prefix = \"tmp\") {\n paste0(prefix, i <<- i + 1L)\n }\n})\n"], ["/quickr/R/compile-package.R", "\n\n\n#' Compile all `quick()` functions in a package.\n#'\n#' This will compile all `quick()` functions in an R package, and\n#' generate source files in the `src/` directory.\n#'\n#' Note, this function is automatically invoked during a `pkgload::load_all()` call.\n#'\n#' @param path Path to an R package\n#'\n#' @returns Called for its side effect.\n#' @export\ncompile_package <- function(path = \".\") {\n if (path != \".\") {\n owd <- setwd(path)\n on.exit(setwd(owd), add = TRUE)\n }\n\n if (!dir.exists(\"R\") || !file.exists(\"DESCRIPTION\"))\n stop(path, \" does not appear to be an R package.\")\n\n pkgname <- read.dcf(\"DESCRIPTION\", \"Package\")\n if (length(pkgname) != 1)\n stop(sprintf(\"path '%s' does not point to an R package\", path))\n pkgname <- as.character(pkgname)\n\n # collect all `quick()` calls in the package\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n\n # TODO: need to unset various R_* env vars, or just\n # take a dep on callr\n system2(file.path(R.home(\"bin\"), \"R\"),\n c(\"-q\", \"-e\", shQuote(\"pkgload::load_all()\")))\n}\n\n\ndump_collected <- function() {\n\n collected <- collector$get_collected()\n\n # try to resolve closure names for anonymous functions\n pkg_ns <- topenv(environment(collected[[1L]]$closure))\n pkg_funcs <- as.list.environment(pkg_ns, all.names = TRUE)\n tab <- hashtab(\"address\", length(collected))\n for (i in seq_along(pkg_funcs)) {\n if (typeof(fn <- pkg_funcs[[i]]) == \"closure\")\n # if is quick closure ...\n sethash(tab, pkg_funcs[[i]], names(pkg_funcs)[i])\n }\n\n quick_funcs <- unlist(recursive = FALSE, lapply(collected, function(x) {\n if (!startsWith(x$name, \"anonymous_quick_function_\"))\n return(setNames(list(x$closure), x$name))\n true_name <- gethash(tab, x$quick_closure)\n if (is.null(true_name))\n return(setNames(list(x$closure), x$name))\n # update pkg_ns with true name\n quick_closure <- create_quick_closure(true_name, x$closure)\n pkg_ns[[true_name]] <- quick_closure\n remhash(tab, x$quick_closure)\n setNames(list(x$closure), true_name)\n }))\n\n\n pkgname <- basename(normalizePath(\".\"))\n\n # check if we have a useDynLib line in NAMESPACE.\n if (!any(sapply(parse(file = \"NAMESPACE\"), function(e) {\n identical(e[[1]], quote(useDynLib)) && isTRUE(e$.registration)\n })))\n message(\"- Please add this roxygen directive somewhere in the Package R sources:\\n \",\n glue(\"#' @useDynLib {pkgname}, .registration = TRUE\"), \"\\n\",\n \"- Then run `devtools::document()`\\n\")\n\n sources <- zip_lists(imap(quick_funcs, function(func, name) {\n fsub <- new_fortran_subroutine(name, func)\n cbridge <- make_c_bridge(fsub, headers = name == names(quick_funcs)[1])\n list(f90 = fsub, c = cbridge)\n })) |> lapply(\\(x) x |> unlist() |> interleave(\"\\n\"))\n\n entries <- paste0(sprintf(' {\"%1$s\", (DL_FUNC) &%1$s, -1}',\n paste0(names(quick_funcs), \"_\")),\n collapse = \",\\n\")\n entries <- sprintf(\"static const R_ExternalMethodDef QuickrEntries[] = {\\n%s\\n};\",\n entries)\n\n append(sources$c) <- c(\"\", entries, \"\")\n\n R_init_pkg <- paste0(\"R_init_\", pkgname, \"(\")\n has_pkg_init_fn <- list.files(\"src\", pattern = \"\\\\.(c|cpp|h|hpp|c\\\\+\\\\+)$\",\n recursive = TRUE, all.files = TRUE,\n full.names = TRUE) |>\n setdiff(\"src/quickr_entrypoints.c\") |>\n lapply(function(f) {\n any(grepl(R_init_pkg, readLines(f, warn = FALSE), fixed = TRUE))\n }) |> unlist() |> any()\n\n append(sources$c) <- c(\"#include <R_ext/Rdynload.h>\", \"\")\n\n init_fn <- if (has_pkg_init_fn) {\n glue(\"\n void R_init_{pkgname}_quick_functions(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n }}\")\n } else {\n init_pkgname <- gsub(\".\", \"_\", pkgname, fixed = TRUE)\n glue(\"\n void R_init_{init_pkgname}(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n R_useDynamicSymbols(dll, FALSE);\n }}\")\n }\n\n append(sources$c) <- init_fn\n\n sources <- lapply(sources, str_split_lines)\n\n src_files_written <- FALSE\n if (!file.exists(\"src\")) dir.create(\"src\")\n cbridges_filepath <- \"src/quickr_entrypoints.c\"\n if (!file.exists(cbridges_filepath) || !identical(sources$c, readLines(cbridges_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(cbridges_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$c, cbridges_filepath)\n cli::cli_inform(c(i = \"Updated {.file {cbridges_filepath}}\"))\n src_files_written <- TRUE\n }\n\n fsubs_filepath <- \"src/quickr_sub_routines.f90\"\n if (!file.exists(fsubs_filepath) || !identical(sources$f90, readLines(fsubs_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(fsubs_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$f90, fsubs_filepath)\n cli::cli_inform(c(i = \"Updated {.file {fsubs_filepath}}\"))\n src_files_written <- TRUE\n }\n\n if (src_files_written) {\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_all)) {\n defer(pkgload::load_all(), sys.frame(i), after = TRUE)\n rlang::return_from(sys.frame(i), value = invisible())\n break\n }\n }\n }\n invisible()\n}\n\npkg_dll_path <- function (pkgname) {\n file.path(\"src\", paste0(pkgname, .Platform$dynlib.ext))\n}\n\n\ncollector <- local({\n\n .collected <- NULL\n\n activate <- function(name = NULL) {\n .collected <<- list()\n attr(.collected, \"name\") <<- name\n }\n\n is_active <- function() {\n is.list(.collected)\n }\n\n add <- function(...) {\n .collected[[length(.collected)+1L]] <<- list(...)\n }\n\n get_collected <- function(clear = TRUE) {\n if (clear)\n on.exit(.collected <<- NULL)\n .collected\n }\n\n environment()\n})\n"], ["/quickr/R/aaa-utils.R", "#' @importFrom glue glue glue_data trim as_glue glue_collapse single_quote\n#' @importFrom dotty .\n#' @importFrom stats setNames\n#' @importFrom utils gethash hashtab remhash sethash str\nNULL\n\n# @export\n# This will be exported by S7 next release.\n`:=` <- function(left, right) {\n name <- substitute(left)\n if (!is.symbol(name))\n stop(\"left hand side must be a symbol\")\n\n right <- substitute(right)\n if (!is.call(right))\n stop(\"right hand side must be a call\")\n\n if (is.symbol(cl <- right[[1L]]) &&\n as.character(cl) %in% c(\"function\", \"new.env\")) {\n # attach \"name\" attr for usage like:\n # foo := function(){}\n # foo := new.env()\n right <- eval(right, parent.frame())\n attr(right, \"name\") <- as.character(name)\n } else {\n # for all other usage,\n # inject name as a named arg, so that\n # foo := new_class(...)\n # becomes\n # foo <- new_class(..., name = \"foo\")\n\n right <- as.call(c(as.list(right), list(name = as.character(name))))\n\n ## skip check; if duplicate 'name' arg is an issue the call itself will signal an error.\n # if (hasName(right, \"name\")) stop(\"duplicate `name` argument.\")\n\n ## alternative code path that injects `name` as positional arg instead\n # right <- as.list(right)\n # right <- as.call(c(right[[1L]], as.character(name), right[-1L]))\n }\n\n eval(call(\"<-\", name, right), parent.frame())\n}\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\n`append<-` <- function(x, after, value) {\n if (missing(after))\n c(x, value)\n else\n append(x, value, after = after)\n}\n\n`append1<-` <- function (x, value) {\n stopifnot(is.list(x) || identical(mode(x), mode(value)))\n x[[length(x) + 1L]] <- value\n x\n}\n\n`prepend<-` <- function(x, value) {\n c(vector(typeof(x)), value, x)\n}\n\n`add<-` <- `+` #function(x, value) x + value\n\nmap_int <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = 0L, ...)\nmap_lgl <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)\nmap_chr <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = \"\", ...)\n\nimap <- function (.x, .f, ...) {\n out <- .mapply(.f, list(.x, names(.x) %||% seq_along(.x)),\n list(...))\n names(out) <- names(.x)\n out\n}\n\nmap2 <- function (.x, .y, .f, ...) {\n if (length(.x) != length(.y) && length(.x) != 1L && length(.y) != 1L)\n stop(\".x and .y must have the same length, or one of them must have length 1\")\n out <- .mapply(.f, list(.x, .y), list(...))\n if (length(.x) == length(out))\n names(out) <- names(.x)\n out\n}\n\ndiscard <- function(.x, .f, ...)\n .x[!vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\nkeep <- function(.x, .f, ...)\n .x[vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\ncompact <- function(.x)\n .x[as.logical(lengths(.x, use.names = FALSE))]\n\ndrop_nulls <- function(x, i) {\n if (missing(i))\n x[!vapply( X = x, FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)]\n else {\n drop <- logical(length(x))\n names(drop) <- names(x)\n drop[i] <- vapply(X = x[i], FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)\n x[!drop]\n }\n}\n\nlast <- function(x) x[[length(x)]]\ndrop_last <- function(x) x[-length(x)]\n\nis_scalar_na <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && is.na(x)\nis_scalar_atomic <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_scalar_integer <- function(x) is.integer(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_string <- function(x) is.character(x) && length(x) == 1L && !is.na(x) # could also be 'glue' class.\nis_bool <- function(x) is.logical(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_number <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_wholenumber <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x) &&\n x >= 0L && (is.integer(x) || is.double(x) && trunc(x) == x)\n\nnew_function <- function(args = NULL, body = NULL, env = parent.frame()) {\n as.function.default(c(args, body %||% list(NULL)), env)\n}\n\nis_call <- function(x, name = NULL) {\n is.call(x) && (is.null(name) || identical(as.symbol(name), x[[1L]]))\n}\n\nstr_flatten <- function(x, collapse = \"\") {\n paste0(as.character(unlist(x, use.names = FALSE)), collapse = collapse)\n}\n\nstr_flatten_lines <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \"\\n\")\n}\n\nstr_flatten_commas <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \", \")\n}\n\nstr_flatten_args <- function(..., multiline = length(dots) >= 3) {\n dots <- unlist(c(character(), ...), use.names = FALSE)\n if (multiline) {\n dots <- paste0(\"\\n \", dots, collapse = \",\")\n paste(dots, \"\\n\")\n } else {\n paste0(dots, collapse = \",\")\n }\n}\n\ninterleave <- function(x, y) {\n stopifnot(is.atomic(x), is.atomic(y), length(y) == 1L, typeof(x) == typeof(y))\n drop_last(as.vector(rbind(x, y, deparse.level = 0L)))\n}\n\nstr_split_lines <- function(...) {\n x <- c(...) |>\n unlist(use.names = FALSE) |>\n strsplit(\"\\n\", fixed = TRUE)\n x[!lengths(x)] <- \"\"\n x |>\n unlist(use.names = FALSE) |>\n trimws(\"right\")\n}\n\nindent <- function(x, n = 2L) {\n x <- str_split_lines(x)\n x <- sub(\"[ \\t\\r]+$\", \"\", x, perl = TRUE) # trim trailing whitespace\n paste0(strrep(\" \", n), x, collapse = \"\\n\")\n}\n\nparent.pkg <- function(env = parent.frame(2)) {\n if (isNamespace(env <- topenv(env)))\n as.character(getNamespaceName(env)) # unname\n else\n NULL # print visible\n}\n\nset_names <- function(x, nm = x, ...) {\n names(x) <- as.character(\n if (is.function(nm)) nm(names(x), ...)\n else unlist(list(nm, ...), use.names = FALSE)\n )\n x\n}\n\nzip_lists <- function(...) {\n x <- if (...length() == 1L) ..1 else list(...)\n\n if (is.character(nms.1 <- names(x.1 <- x[[1L]])))\n if (anyDuplicated(nms.1) || anyNA(nms.1) || any(nms.1 == \"\"))\n stop(\"All names must be unique.\",\n \" (Use `unname()` for positional matching.)\")\n\n if (length(setdiff(lengths(x), 1L)) != 1L)\n stop(\"all elements must have the same length\")\n\n for (i in seq_along(x)) {\n if (identical(nms.1, nms.i <- names(x[[i]])))\n next\n if (setequal(nms.1, nms.i)) {\n x[[i]] <- x[[i]][nms.1]\n next\n }\n stop(\"All names of arguments provided to `zip_lists()` must match.\",\n \" Call `unname()` on each argument if you want positional matching\")\n }\n ans <- .mapply(list, x, NULL)\n names(ans) <- nms.1\n ans\n}\n\nis_missing <- function(x) missing(x) || identical(x, quote(expr = ))\n\nis_type_call <- function(e) {\n is.call(e) && identical(e[[1]], quote(type))\n}\n\nreduce <- function (.x, .f, ..., .init) {\n f <- function(x, y) .f(x, y, ...)\n Reduce(f, .x, init = .init)\n}\n\nsubstitute_ <- function(expr, env) {\n do.call(base::substitute, list(expr, env))\n}\n\ndefer <- function (expr, env = parent.frame(), after = FALSE) {\n thunk <- as.call(list(function() expr))\n do.call(on.exit, list(thunk, TRUE, after), envir = env)\n}\n\nis_scalar <- function(x) identical(length(x), 1L)\n"], ["/quickr/R/classes.R", "#' @import S7\nNULL\n\nnew_setter <- function(coerce = NULL, coerce_null = FALSE, set_once = FALSE, env = parent.frame(2L)) {\n\n if (is.null(coerce) || isFALSE(coerce) && isFALSE(set_once))\n return()\n\n bind_name <- quote(name <- as.character(last(attr(self, \".setting_prop\", TRUE))))\n\n check_set_once <- if (set_once) {\n quote(if (!is.null(prop(self, name)))\n stop(name, \" can only be set once\"))\n }\n\n rebind_coerced_value <-\n if (is.null(coerce) || isFALSE(coerce)) {\n NULL\n } else if (isTRUE(coerce)) {\n quote(value <- convert(\n from = value,\n to = S7_class(self)@properties[[as.character(name)]]$class\n ))\n } else if (is.function(coerce) || is.symbol(coerce)) {\n bquote(value <- .(coerce)(value))\n } else if (is.language(coerce)) {\n bquote(value <- .(coerce))\n } else {\n stop(\"coerce must be TRUE, FALSE, NULL, a function, a symbol, or a call\")\n }\n\n if (!coerce_null && !is.null(rebind_coerced_value)) {\n rebind_coerced_value <- bquote(if (!is.null(value)) .(rebind_coerced_value))\n }\n\n set <- quote(`prop<-`(\n object = self,\n name = name,\n check = FALSE,\n value = value\n ))\n\n new_function(\n args = alist(self = , value = ),\n body = as.call(c(quote(`{`),\n bind_name,\n check_set_once,\n rebind_coerced_value,\n set)),\n env = env\n )\n}\n\n\nnew_scalar_validator <- function(allow_null = FALSE,\n allow_na = FALSE,\n additional_checks = NULL,\n env = parent.frame(2L)) {\n checks <- c(\n if (allow_null) quote(if (is.null(value)) return()),\n quote(if (length(value) != 1L) return(\"must be a scalar\")),\n if (!allow_na) quote(if (anyNA(value)) return(\"must not be NA\")),\n additional_checks\n )\n\n new_function(\n args = alist(value = ),\n body = as.call(c(quote(`{`), checks)),\n env = parent.frame(2L)\n )\n}\n\n\nprop_bool <- function(default, allow_null = FALSE, allow_na = FALSE, set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n new_property(\n class = if (allow_null) NULL | class_logical else class_logical,\n setter = new_setter(set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null,\n allow_na = allow_na),\n default = default\n )\n}\n\n\nprop_string <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = FALSE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(as.character)\n\n new_property(\n class = if (allow_null) NULL | class_character else class_character,\n default = default,\n validator = new_scalar_validator(allow_null = allow_null),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once)\n )\n}\n\n\nprop_wholenumber <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = TRUE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(\n if (is_wholenumber(value)) as.integer(value)\n else stop(\"@\", name, \" must be a whole number, but received: \", value)\n )\n\n new_property(\n class = if (allow_null) NULL | class_integer else class_integer,\n default = as.integer(default),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null)\n )\n}\n\n\nprop_enum <- function(values,\n nullable = FALSE,\n default = if (nullable) NULL else values[1],\n exact = FALSE,\n set_once = FALSE) {\n\n stopifnot(\n \"values must be a character vector of length >= 2 without any NA\" =\n is.character(values) && length(values) >= 2 && !anyNA(values)\n )\n\n coerce <- if (exact) NULL else {\n bquote(if (length(value) == 1L && !anyNA(i <- charmatch(value, .(values))))\n .(values)[i] else value)\n }\n\n display_values <- glue_collapse(single_quote(values), sep = \", \", last = \", or \")\n msg <- sprintf(\"must be either %s, not '\", display_values)\n validator <- new_scalar_validator(allow_null = nullable,\n additional_checks = bquote(\n if (!match(value, .(values), nomatch = 0L))\n return(paste0(.(msg), value, \"'.\"))\n ))\n\n new_property(\n class = if (nullable) NULL | class_character else class_character,\n setter = new_setter(coerce = coerce, coerce_null = !nullable, set_once = set_once),\n validator = validator,\n default = default\n )\n}\n\n\n.atomic_type_names <- c(\"integer\", \"logical\", \"double\",\n \"character\", \"raw\", \"complex\")\n\n\n# the print method for this should only print non-null values\nVariable := new_class(\n properties = list(\n\n mode = prop_enum(.atomic_type_names, nullable = TRUE, set_once = FALSE),\n\n dims = new_property(\n # NULL means scalar\n NULL | class_list,\n setter = function(self, value) {\n if (!length(value))\n return(self)\n\n value <- switch(typeof(value),\n logical = , integer = , double = as.list(value),\n language = , symbol = list(value), # implicit rank-1\n list = value,\n stop(\"@dims must be a list\")\n )\n\n value <- lapply(value, \\(axis) {\n if (is.language(axis)) {\n axis\n } else if (is_wholenumber(axis) || is_scalar_na(axis)) {\n as.integer(axis)\n } else {\n stop(sprintf(\n \"%s@dims must be a list of language or scalar integers, not %s\",\n self@name %||% '', axis\n ))\n }\n })\n\n self@dims <- value\n self\n } # dims$setter\n ), # dims = new_property()\n\n name = prop_string(\n allow_null = TRUE,\n coerce = quote(switch(typeof(value), symbol = as.character(value), value)),\n set_once = FALSE #TRUE\n ),\n\n rank = new_property(\n class_integer,\n getter = function(self) {\n length(self@dims)\n }),\n\n modified = prop_bool(default = FALSE),\n\n r = new_property(\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n # custom setter to workaround https://github.com/RConsortium/S7/issues/511\n attr(self, \"r\") <- value\n self\n }\n ),\n\n is_arg = prop_bool(default = FALSE),\n\n is_return = prop_bool(default = FALSE),\n\n # TRUE for closure args and return values, FALSE for all other vars.\n is_external = new_property(\n class_logical,\n getter = function(self)\n self@is_arg || self@is_return\n ),\n\n is_scalar = new_property(\n class_logical,\n getter = function(self) {\n self@rank == 0 || identical(self@dims, list(1L))\n }\n )\n\n )\n)\n\n# method(print, Variable) <- function(x, ...) {\n#\n# }\n\n\n\nFortran := new_class(\n class_character,\n\n properties = list(\n\n value = NULL | Variable,\n\n r = new_property(\n # custom setter only to workaround https://github.com/RConsortium/S7/issues/511\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n attr(self, \"r\") <- value\n self\n }\n )\n ),\n\n validator = function(self) {\n if (length(self) != 1L)\n \"must be a length 1 string\"\n }\n)\n\n\nFortranSubroutine := new_class(Fortran, properties = list(\n name = prop_string(),\n signature = class_character,\n closure = class_function,\n scope = NULL | class_environment,\n c_bridge = S7::new_property(\n NULL | class_character,\n getter = function(self) {\n make_c_bridge(self) %error% NULL\n })\n))\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\ntry_prop <- function(object, name) S7::prop(object, name) %error% NULL\n\nemit <- function(..., sep = \"\", end = \"\\n\") cat(..., end, sep = sep)\n\nmethod(format, Variable) <- function(x, ...) {\n capture.output(str(x))\n}\n\nmethod(as.character, Variable) <- function(x, ...)\n x@name %||% stop(\"Variable does not have a name\")\n\nmethod(print, Fortran) <- function(x, ...) {\n emit(trimws(x), end = \"\\n\\n\")\n for(prop_name in c(\"value\", \"r\", \"c_bridge\"))\n if (!is.null(prop_val <- try_prop(x, prop_name))) {\n emit(\"@\", prop_name, \": \", trimws(indent(format(prop_val))));\n }\n}\n"], ["/quickr/R/scope.R", "\n\nnew_ordered_env <- function(parent = emptyenv()) {\n env <- new.env(parent = parent)\n class(env) <- \"quickr_ordered_env\"\n env\n}\n\n#' @export\n`[[<-.quickr_ordered_env` <- function(x, name, value) {\n attr(x, \"ordered_names\") <- unique(c(attr(x, \"ordered_names\", TRUE), name))\n assign(name, value, envir = x)\n x\n # NextMethod()\n}\n\n#' @export\n`[[.quickr_ordered_env` <- function(x, name) {\n get0(name, x) # name can be a symbols too\n}\n\n#' @export\nnames.quickr_ordered_env <- function(x) {\n all_names <- ls(envir = x, sorted = FALSE)\n ordered_names <- attr(x, \"ordered_names\", TRUE)\n if (!setequal(all_names, ordered_names)) {\n warning(\"untracked name\")\n stop(\"untracked name\")\n }\n ordered_names\n}\n\n#' @export\nas.list.quickr_ordered_env <- function(x, ...) {\n out <- as.list.environment(x, all.names = TRUE, ...)\n out[names.quickr_ordered_env(x)]\n}\n\n#' @export\nprint.quickr_ordered_env <- function(x, ...) {\n emit(\"env (class: \", str_flatten_commas(class(x)), \") with bindings:\")\n str(as.list.quickr_ordered_env(x), no.list = TRUE)\n}\n\n\ncheck_assignment_compatible <- function(target, value) {\n if (is.null(value)) return()\n stopifnot(exprs = {\n inherits(target, Variable)\n inherits(value, Variable)\n passes_as_scalar(target) || passes_as_scalar(value) || target@rank == value@rank\n })\n}\n\nnew_scope <- function(closure, parent = emptyenv()) {\n scope <- new_ordered_env(parent = parent)\n class(scope) <- unique(c(\"quickr_scope\", class(scope)))\n attr(scope, \"closure\") <- closure\n\n\n attr(scope, \"get_unique_var\") <- local({\n i <- 0L\n function(...) {\n name <- paste0(\"tmp\", i <<- i + 1L, \"_\")\n (scope[[name]] <- Variable(..., name = name))\n }\n })\n attr(scope, \"assign\") <- function(name, value) {\n stopifnot(inherits(value, Variable), is.symbol(name) || is_string(name))\n name <- as.character(name)\n if (exists(name, scope))\n check_assignment_compatible(get(name, scope), value)\n value@name <- name\n assign(name, value, scope)\n }\n scope\n}\n\n\n#' @export\n`@.quickr_scope` <- function(x, name) attr(x, name, exact = TRUE)\n\n#' @export\n`@<-.quickr_scope` <- function(x, name, value) `attr<-`(x, name, value = value)\n\n#' @importFrom utils .AtNames findMatches\n#' @export\n.AtNames.quickr_scope <- function(x, pattern = \"\")\n findMatches(pattern, names(attributes(x)))\n\n"], ["/quickr/R/preprocess-lang.R", "\n\ndefuse_numeric_literals <- function(e) {\n if (is.call(e)) {\n e <- as.call(lapply(e, defuse_numeric_literals))\n if (is.symbol(e1 <- e[[1L]]) &&\n as.character(e1) %in% c(\"+\", \"-\", \"*\", \"/\", \"%%\", \"%/%\", \"^\") &&\n all(map_lgl(e[-1L], is.atomic))) {\n e <- eval(e, baseenv())\n }\n }\n e\n}\n\n\nensure_last_expr_sym <- function(bdy) {\n if (!is_call(bdy, quote(`{`)))\n stop(\"bad body, needs {\")\n if (!is.symbol(last_expr <- last(bdy))) {\n bdy[[length(bdy)]] <- call(\"<-\", quote(out_), last_expr)\n bdy[[length(bdy) + 1L]] <- quote(out_)\n }\n bdy\n}\n\n\nwhole_doubles_to_ints <- function(x) {\n walker <- function(x) {\n switch(\n typeof(x),\n double = if (trunc(x) == x) as.integer(x),\n language = as.call(lapply(x, walker)),\n list = lapply(x, walker),\n x\n )\n }\n walker(x)\n}\n"], ["/quickr/R/zzz.R", "# # ' @export\n# `@.default` <- function(x, name) {\n# if (isS4(x))\n# methods::slot(x, name)\n# else\n# attr(x, name, TRUE)\n# }\n#\n# # ' @export\n# `@<-.default` <- function(x, name, value) {\n# if (isS4(x))\n# methods::`slot<-`(x, name, value = value)\n# else\n# `attr<-`(x, name, value)\n# }\n#\n# # ' @importFrom utils .AtNames findMatches\n# .AtNames.default <- function(x, pattern = \"\") {\n# if (isS4(x))\n# findMatches(pattern, methods::slotNames(x))\n# else\n# findMatches(pattern, names(attributes(x)))\n# }\n#\n# on_load_register_.AtNames.default <- function() {\n# # if we register via NAMESPACE, we get warning\n# # about overwriting utils:::.AtNmaes.default\n# registerS3method(\".AtNames\", \"default\", .AtNames.default)\n# }\n\n.onLoad <- function(...) {\n S7::methods_register()\n asNamespace(\"dotty\")$dotify()\n # on_load_register_.AtNames.default()\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-21 01:15:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(var) {}", "code_description": "This code segment functions to: Generate Fortran variable declarations by determining data types, parameter intents, and array dimensions based on input variable properties and usage context."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(var) {\n # Check if any dimension contains NA (unspecified size)\n allocatable <- any(sapply(var@dims, \\(d) is.language(d) && any(is.na(d))))\n \n # Build Fortran declaration components\n type <- switch(var@type,\n integer = \"integer\",\n real = \"real\",\n logical = \"logical\",\n complex = \"complex\",\n character = \"character(len=*)\"\n )\n \n dim_spec <- dims2f(var@dims, parent.frame())\n dim_str <- if (nzchar(dim_spec)) glue(\", dimension({dim_spec})\") else \"\"\n alloc_str <- if (allocatable && !var@is_arg) \", allocatable\" else \"\"\n intent <- if (var@is_arg) \"intent(inout)\" else if (var@modified) \"intent(out)\" else NULL\n \n # Compose full declaration\n decl <- glue(\"{type}{dim_str}{alloc_str} :: {var@name}\")\n if (!is.null(intent)) decl <- glue(\"integer, intent(in) :: {var@name}_size\\n{decl}\")\n \n decl\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-16-11"}, "editdistance_info": {"edit_distance": 13.0841, "calculate_time": "2025-08-21 01:16:11", "true_code_clean": "function(var) {\n intent_in <- var@name %in% names(formals(scope@closure))\n intent_out <- var@name == closure_return_var_name(scope@closure) || intent_in && var@modified\n intent <-\n if (intent_in && intent_out) \"intent(in out)\"\n else if (intent_in) \"intent(in)\"\n else if (intent_out) \"intent(out)\"\n else NULL\n type <- switch(var@mode,\n double = \"real(c_double)\",\n integer = \"integer(c_int)\",\n complex = \"complex(c_double_complex)\",\n logical = if (intent_in || intent_out) \"integer(c_int)\" else \"logical\",\n raw = \"integer(c_int8_t)\",\n stop(\"unrecognized kind: \", format(var))\n )\n dims <- if (passes_as_scalar(var)) {\n NULL\n } else {\n dims2f(var@dims, scope) |> str_flatten_commas() |> sprintf(fmt = \"(%s)\")\n }\n allocatable <- if (!is.null(dims) && grepl(\":\", dims, fixed = TRUE))\n \"allocatable\"\n if (intent_in && intent_out && !is.null(allocatable))\n stop(\"all input and output vars must have a fully defined shape\")\n name <- var@name\n comment <- if (var@mode == \"logical\") \" ! logical\"\n glue('{str_flatten_commas(type, intent, allocatable)} :: {name}{dims}{comment}',\n .null = \"\")\n }", "predict_code_clean": "function(var) {\n allocatable <- any(sapply(var@dims, \\(d) is.language(d) && any(is.na(d))))\n type <- switch(var@type,\n integer = \"integer\",\n real = \"real\",\n logical = \"logical\",\n complex = \"complex\",\n character = \"character(len=*)\"\n )\n dim_spec <- dims2f(var@dims, parent.frame())\n dim_str <- if (nzchar(dim_spec)) glue(\", dimension({dim_spec})\") else \"\"\n alloc_str <- if (allocatable && !var@is_arg) \", allocatable\" else \"\"\n intent <- if (var@is_arg) \"intent(inout)\" else if (var@modified) \"intent(out)\" else NULL\n decl <- glue(\"{type}{dim_str}{alloc_str} :: {var@name}\")\n if (!is.null(intent)) decl <- glue(\"integer, intent(in) :: {var@name}_size\\n{decl}\")\n decl\n}"}}
{"repo_name": "quickr", "file_name": "/quickr/R/c-wrapper.R", "inference_info": {"prefix_code": "\nmake_c_bridge <- ", "suffix_code": "\n\n\nclosure_arg_c_defs <- function(var, strict = TRUE) {\n\n name <- var@name\n mode <- var@mode\n\n c_code <- character()\n\n name <- var@name\n SEXPTYPE <- sexptype(var@mode)\n protect <- glue(\"SETCAR(_args, {var@name});\")\n\n append(c_code) <- glue(\n \"// {name}\n _args = CDR(_args);\n SEXP {var@name} = CAR(_args);\")\n\n # first maybe duplicate or coerce the SEXP if needed.\n append(c_code) <- glue(\"if (TYPEOF({name}) != {SEXPTYPE}) {{\")\n append(c_code) <- indent(if (strict) {\n glue(r\"(\n Rf_error(\"typeof({name}) must be '{mode}', not '%s'\", R_typeToChar({name}));\n )\")\n } else {\n glue(\"{name} = Rf_coerceVector({name}, {SEXPTYPE});\n {protect}\")\n })\n\n\n if (var@modified) {\n dup <- glue('\n {name} = Rf_duplicate({name});\n {protect}\n ')\n\n if (strict) {\n append(c_code) <- c(\"}\", dup)\n } else {\n append(c_code) <- sprintf(\"} else %s\", dup)\n }\n\n } else {\n append(c_code) <- \"}\"\n }\n\n # define the variable that will be passed to the fsub\n append(c_code) <- glue(\n \"{fsub_arg_var_c_type(var)} {name}__ = {sexpdata(var@mode)}({name});\")\n\n\n if (var@rank == 1) {\n size_name <- get_size_name(var)\n append(c_code) <- glue(\"const R_xlen_t {size_name} = Rf_xlength({var@name});\")\n } else if (var@rank > 1) {\n append(c_code) <- glue(\n 'const int* const {var@name}__dim_ = ({{\n SEXP dim_ = Rf_getAttrib({var@name}, R_DimSymbol);\n if (Rf_length(dim_) != {var@rank}) Rf_error(\n \"{var@name} must be a {var@rank}D-array, but length(dim({var@name})) is %i\",\n (int) Rf_length(dim_));\n INTEGER(dim_);}});'\n )\n append(c_code) <- map_chr(seq_len(var@rank), \\(axis) {\n size_name <- get_size_name(var, axis)\n glue(\"const int {size_name} = {var@name}__dim_[{axis-1}];\")\n })\n } else {\n stop(\"bad rank\")\n }\n\n as_glue(str_flatten_lines(c_code))\n}\n\n\n\nclosure_arg_size_checks <- function(var, scope) {\n imap(var@dims, function(d, axis) {\n # axis is either:\n # - an integer\n # - a symbol of a size_name\n # - a call, consisting of only size_name symbols and basic arithmetic ops.\n size_name <- get_size_name(var, axis)\n\n if (is_scalar_integer(d)) {\n return(glue('\n if ({size_name} != {d})\n Rf_error(\"{friendly_size(var, axis)} must be {d}, not %0.f\",\n (double){size_name});'\n ))\n }\n\n if (is.symbol(d)) {\n if (as.character(d) == size_name) {\n # self-named size_name is expected to be passed along to subroutine\n return()\n } else {\n # it's a constraint for another size\n return(glue('\n if ({d} != {size_name})\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_name(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double){d});'\n ))\n }\n }\n\n if (is.call(d)) {\n size.c <- dims2c(list(d), scope)\n return(glue('{{\n const R_xlen_t expected = {size.c};\n if ({size_name} != expected)\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_expression(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double)expected);\n }}'\n ))\n }\n\n stop(\"bad dim\")\n })\n}\n\n\n\n\nreturn_var_c_defs <- function(var, scope) {\n # allocate the return var.\n name <- var@name\n c_dims <- dims2c(var@dims, scope)\n c_len <- c_dims2c_len(c_dims)\n len_name <- get_size_name(var)\n\n c_code <- c(\n glue(\"const R_xlen_t {len_name} = {c_len};\"),\n glue(switch(\n var@mode,\n double = \"\n SEXP {name} = PROTECT(Rf_allocVector(REALSXP, {len_name}));\n double* {name}__ = REAL({name});\",\n integer = \"\n SEXP {name} = PROTECT(Rf_allocVector(INTSXP, {len_name}));\n int* {name}__ = INTEGER({name});\",\n complex = \"\n SEXP {name} = PROTECT(Rf_allocVector(CPLXSXP, {len_name}));\n Rcomplex* {name}__ = COMPLEX({name});\",\n logical = \"\n SEXP {name} = PROTECT(Rf_allocVector(LGLSXP, {len_name}));\n int* {name}__ = LOGICAL({name});\"\n )))\n\n if (var@rank > 1) {\n append(c_code) <- c_block(\n glue(\"\n const SEXP _dim_sexp = PROTECT(Rf_allocVector(INTSXP, {var@rank}));\n int* const _dim = INTEGER(_dim_sexp);\"\n ),\n imap(c_dims, function(d, i) {\n glue(\"_dim[{i-1}] = {d};\")\n }),\n glue(\"Rf_dimgets({var@name}, _dim_sexp);\")\n )\n }\n\n str_flatten_lines(c_code)\n}\n\n\n\n\ndims2c_eval_base_env <- new.env()\n\n\ndims2c_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\ndims2c_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2c_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2c_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2c_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"((double)({e1}) / (double)({e2}))\")\n# dividing integers truncates towards 0\ndims2c_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} / (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} % (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1}**{e2})\")\n\n\ndims2c <- function(dims, scope) {\n if (!length(dims) || identical(dims, list(1L))) {\n return(list(NULL, \"1\"))\n }\n\n syms <- as.character(unique(unlist(lapply(dims, all.vars))))\n\n syms <- mget(syms, scope, ifnotfound = syms) |>\n lapply(function(var) {\n if (is_size_name(var)) {\n return(as.character(var))\n }\n # resolve a variable from scope (i.e., some other arg var)\n if (!inherits(var, Variable))\n stop(\"could not resolve size: \", var)\n glue(\"Rf_asInteger({var@name})\")\n # Should this be as double?\n # TODO: force this into a named c var, to avoid repeated calls\n })\n\n eval_env <- list2env(syms, parent = dims2c_eval_base_env)\n c_dims <- lapply(dims, function(d) {\n if (inherits(d, Variable))\n return(glue(\"Rf_asInteger({d@name})\"))\n eval(d, eval_env)\n })\n\n c_dims\n}\n\nc_dims2c_len <- function(c_dims) {\n if (length(c_dims) == 1)\n c_dims[[1L]]\n else\n paste0(\"(\", unlist(c_dims), \")\", collapse = \" * \" )\n # eval(Reduce(\\(a, b) { call(\"*\", as.symbol(a@name), as.symbol(b@name)) }, dims),\n # eval_env)\n}\n\n\n# --- utils ----\n\nc_block <- function(...) {\n as_glue(paste0(c(\"{\", indent(c(...)), \"}\"), collapse = \"\\n\"))\n}\n\n# is_var_size <- function(x) inherits(x, VariableSize)\n\npasses_as_scalar <- function(var) {\n var@rank == 0 || var@rank == 1 && identical(var@dims, list(1L))\n}\n\npasses_as_value <- function(var) {\n passes_as_scalar(var) && isFALSE(var@modified)\n}\n\nsexptype <- function(mode) {\n switch(mode,\n integer = \"INTSXP\",\n double = \"REALSXP\",\n complex = \"CPLXSXP\",\n logical = \"LGLSXP\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nsexpdata <- function(mode) {\n switch(mode,\n integer = \"INTEGER\",\n double = \"REAL\",\n complex = \"COMPLEX\",\n logical = \"LOGICAL\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nis_size_name <- function(name) {\n if (is.symbol(name)) {\n name <- as.character(name)\n } else if (!is_string(name)) {\n return(FALSE)\n }\n\n grepl(\"(_len_|_dim_[0-9]+_)$\", name)\n}\n\nfriendly_size <- function(var, axis = NULL) {\n if (is.null(axis) || var@rank == 1 && axis == 1)\n glue(\"length({var@name})\")\n else\n glue(\"dim({var@name})[{axis}]\")\n}\n\nas_friendly_size_name <- function(size_name) {\n size_name <- as.character(size_name)\n if (endsWith(size_name, \"__len_\"))\n sprintf(\"length(%s)\", sub(\"__len_$\", \"\", size_name))\n else\n sub(\"^(.*)__dim_([0-9]+)_$\", \"dim(\\\\1)[\\\\2]\", size_name)\n}\n\nas_friendly_size_expression <- function(d) {\n stopifnot(is.call(d))\n nms <- all.names(d, functions = FALSE, unique = TRUE)\n friendly_substitutions <- new.env(parent = emptyenv())\n for(name in nms)\n if (is_size_name(name))\n assign(name, str2lang(as_friendly_size_name(name)), friendly_substitutions)\n d <- substitute_(d, friendly_substitutions)\n d <- call(\"(\", d)\n deparse1(d)\n}\n\nclosure_return_var_name <- function(closure) {\n return_var_name <- last(body(closure))\n if (!is.symbol(return_var_name))\n stop(\"return value must be a symbol\")\n as.character(return_var_name)\n}\n\n\nfsub_arg_var_c_type <- function(var) {\n type <- switch(var@mode,\n double = \"double*\",\n integer = \"int*\",\n complex = \"Rcomplex*\",\n logical = \"int*\",\n )\n\n # the first const declares that the pointed to values can't be modified\n # (the array values are read only)\n # the second const declares that the pointer itself can't be modified\n # (the fsub can never move/reallocate the array, so this const is always present)\n paste0(c(if (!var@modified) \"const\", type, \"const\"),\n collapse = \" \")\n}\n\nfsub_extern_decl <- function(fsub) {\n fsub_arg_names <- fsub@signature # arg names\n scope <- fsub@scope\n\n fsub_c_sig <- map_chr(fsub_arg_names, function(name) {\n if (is_size_name(name)) {\n type <- if (endsWith(\"__len_\", name))\n \"R_xlen_t\" else \"R_len_t\"\n glue(\"const {type} {name}\")\n } else {\n var <- get(name, fsub@scope)\n glue(\"{fsub_arg_var_c_type(var)} {var@name}__\")\n }\n })\n if (length(fsub_c_sig) >= 3L)\n fsub_c_sig <- paste0(\"\\n \", fsub_c_sig)\n\n glue(\"extern void {fsub@name}({str_flatten_commas(fsub_c_sig)});\")\n}\n", "middle_code": "function(fsub, strict = TRUE, headers = TRUE) {\n stopifnot(inherits(fsub, FortranSubroutine))\n closure <- fsub@closure\n scope <- fsub@scope\n fsub_arg_names <- fsub@signature \n closure_arg_names <- names(formals(closure))\n c_body <- character()\n if (!all(closure_arg_names %in% fsub_arg_names))\n stop(\"Undeclared arguments: \", str_flatten_commas(setdiff(closure_arg_names, fsub_arg_names)))\n closure_arg_vars <- mget(closure_arg_names, scope)\n append(c_body) <- lapply(closure_arg_vars, closure_arg_c_defs, strict = strict) |>\n rbind(\"\")\n append(c_body) <- lapply(closure_arg_vars, closure_arg_size_checks, scope = scope)\n n_protected <- 0L\n return_var <- get(closure_return_var_name(closure), scope)\n if (!return_var@name %in% closure_arg_names) {\n return_var@modified <- TRUE\n assign(return_var@name, return_var, scope)\n append(c_body) <- return_var_c_defs(return_var, fsub@scope)\n add(n_protected) <- 1L \n if (return_var@rank > 1)\n add(n_protected) <- 1L \n }\n fsub_call_args <- fsub_arg_names |>\n lapply(\\(nm) paste0(nm, if (!is_size_name(nm)) \"__\")) |>\n unlist()\n if (length(fsub_call_args) > 3)\n fsub_call_args <- paste0(\"\\n \", fsub_call_args)\n append(c_body) <- c(\"\", glue(\"{fsub@name}({str_flatten_commas(fsub_call_args)});\"), \"\")\n if (n_protected > 0)\n append(c_body) <- glue(\"UNPROTECT({n_protected});\")\n append(c_body) <- glue(\"return {return_var@name};\")\n c_args <- paste(\"SEXP\", names(formals(closure)), collapse = \", \")\n c_body <- as_glue(str_flatten_lines(c_body))\n c_func_def <- glue(\"SEXP {fsub@name}_(SEXP _args) {c_block(c_body)}\")\n fsub_extern_decl <- fsub_extern_decl(fsub)\n c_headers <- glue::trim(r\"--(\n )--\")\n as_glue(str_flatten_lines(c(\n if (headers) c_headers,\n fsub_extern_decl, \"\",\n c_func_def)\n ))\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/quickr/R/r2f.R", "\n\n\n# Take parsed R code (anything returnable by base::str2lang()) and returns\n# a Fortran object, which is a string of Fortran code and some attributes\n# describing the value.\nlang2fortran <- r2f <- function(e, scope = NULL, ..., calls = character(), hoist = NULL) {\n ## 'hoist()' is a function that individual handlers can call to pre-emit some\n ## Fortran code. E.g., to setup a temporary variable if the generated Fortran\n ## code doesn't neatly translate into a single expression.\n hoisted <- character()\n if (is.null(hoist)) {\n delayedAssign(\"hoist_connection\", textConnection(\"hoisted\", \"w\", TRUE))\n hoist <- function(...) {\n writeLines(as.character(unlist(c(character(), ...))),\n hoist_connection)\n }\n # if performance with textConnection() becomes an issue, maybe switch to an\n # anonymous file(), though, each hoisting context is typically shortlived and\n # usually 0 lines are hoisted per context, and if they are hoisted, a small number.\n }\n\n fortran <- switch(typeof(e),\n language = {\n # a call\n handler <- get_r2f_handler(callable <- e[[1L]])\n\n match.fun <- attr(handler, \"match.fun\", TRUE)\n if (is.null(match.fun)) {\n match.fun <- get0(callable, parent.env(globalenv()),\n mode = \"function\")\n # this is a best effort to, eg. resolve `seq.default` from `seq`.\n # This should likely be moved into attaching the `match.fun` attr\n # to handlers, for more involved resolution (e.g., with getS3Method())\n if (\"UseMethod\" %in% all.names(body(match.fun)))\n match.fun <- get0(paste0(callable, \".default\"),\n parent.env(globalenv()),\n mode = \"function\",\n ifnotfound = match.fun)\n }\n if (typeof(match.fun) == \"closure\") {\n e <- match.call(match.fun, e)\n }\n\n if (isTRUE(getOption(\"quickr.r2f.debug\"))) {\n\n try(handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)) -> res\n if (inherits(res, \"try-error\")) {\n debugonce(handler)\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n }\n\n res\n\n } else {\n\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n\n }\n\n },\n\n integer = ,\n double = ,\n complex = ,\n logical = atomic2Fortran(e),\n\n symbol = {\n s <- as.character(e)\n # logicals that come in from R are passed as integer types,\n # so for all fortran ops we cast to logical with /=0\n if (\n !is.null(scope[[e]] -> val) &&\n val@mode == \"logical\" &&\n val@is_external\n ) {\n s <- paste0(\"(\", s, \"/=0)\")\n }\n Fortran(s, value = scope[[e]])\n },\n\n ## handling 'object' and 'closure' here are both bad ideas,\n ## TODO: delete both\n # \"object\" = {\n # if (inherits(e, Variable))\n # e <- Fortran(character(), e)\n # stopifnot(inherits(e, Fortran))\n # e\n # },\n\n closure = {\n if (is.null(name <- attr(e, \"name\", TRUE))) {\n name <- if (is.symbol(name <- substitute(e)))\n as.character(name)\n else\n \"anonymous_function\"\n }\n\n stopifnot(is.null(scope))\n new_fortran_subroutine(name, e)\n },\n\n ## all the other typeof() possible values\n # \"character\",\n # \"raw\" ,\n # \"list\",\n # \"NULL\",\n # \"function\",\n # \"special\",\n # \"builtin\",\n # \"environment\",\n # \"S4\",\n # \"pairlist\",\n # \"promise\",\n # \"char\",\n # \"...\",\n # \"any\",\n # \"expression\",\n # \"externalptr\",\n # \"bytecode\",\n # \"weakref\"\n # default\n stop(\"Unsupported object type encountered: \", typeof(e))\n )\n\n if (length(hoisted)) {\n combined <- str_flatten_lines(c(hoisted, fortran))\n attributes(combined) <- attributes(fortran)\n fortran <- combined\n }\n\n attr(fortran, \"r\") <- e\n fortran\n}\n\n\natomic2Fortran <- function(x) {\n stopifnot(is_scalar_atomic(x))\n s <- switch(typeof(x),\n double =,\n integer = num2fortran(x),\n logical = if (x) \".true.\" else \".false.\",\n complex = sprintf(\"(%s, %s)\", num2fortran(Re(x)), num2fortran(Im(x))))\n Fortran(s, Variable(typeof(x)))\n}\n\nnum2fortran <- function(x) {\n stopifnot(typeof(x) %in% c(\"integer\", \"double\"))\n digits <- 7L\n nsmall <- switch(typeof(x), integer = 0L, double = 1L)\n repeat {\n s <- format.default(x, digits = digits, nsmall = nsmall, scientific = 1L)\n if (x == eval(str2lang(s))) # eval() needed for negative and complex numbers\n break\n add(digits) <- 1L\n if (digits > 22L)\n stop(\"number formatting error: \", x, \" formatted as : \", s)\n }\n paste0(s, switch(typeof(x), double = \"_c_double\", integer = \"_c_int\"))\n}\n\n\nr2f_handlers := new.env(parent = emptyenv())\n\nget_r2f_handler <- function(name) {\n stopifnot(\"All functions called must be named as symbols\" = is.symbol(name))\n get0(name, r2f_handlers) %||% stop(\"Unsupported function: \", name, call. = FALSE)\n}\n\nr2f_default_handler <- function(args, scope = NULL, ..., calls) {\n # stopifnot(is.call(e), is.symbol(e[[1L]]))\n\n x <- lapply(args, r2f, scope = scope, calls = calls, ...)\n s <- sprintf(\"%s(%s)\", last(calls), str_flatten_commas(x[-1]))\n Fortran(s)\n}\n\n## ??? export as S7::convert() methods?\nregister_r2f_handler <- function(name, fun) {\n stopifnot(\n is_string(name),\n identical(formals(fun), alist(x = , scope = NULL))\n )\n\n r2f_handlers[[name]] <- fun\n}\n\n.r2f_handler_not_implemented_yet <- function(e, scope, ...) {\n stop(gettextf(\"'%s' is not implemented yet\", as.character(e[[1L]])),\n call. = FALSE)\n}\n\nr2f_handlers[[\"declare\"]] <- function(args, scope, ...) {\n\n for (a in args) {\n if (is_missing(a)) {\n next\n }\n if (is_type_call(a)) {\n var <- type_call_to_var(a)\n var@is_arg <- var@name %in% names(formals(scope@closure))\n scope[[var@name]] <- var\n } else if (is_call(a, quote(`{`))) {\n Recall(as.list(a)[-1], scope)\n }\n }\n\n Fortran(\"\")\n}\n\n\nr2f_handlers[[\"Fortran\"]] <- function(args, scope = NULL, ...) {\n if (!is_string(args[[1]]))\n stop(\"Fortran() must be called with a string\")\n Fortran(args[[1]])\n # enable passing through literal fortran code\n # used like:\n # Fortran(\"nearest(x, 1)\", double(length(x)))\n # Fortran(\"nearest(x, 1)\", x)\n # Fortran(\"x = nearest(x, 1)\")\n}\n\nr2f_handlers[[\"(\"]] <- function(args, scope, ...) {\n r2f(args[[1L]], scope, ...)\n}\n\nr2f_handlers[[\"{\"]] <- function(args, scope, ..., hoist = NULL) {\n # every top level R-expr / fortran statement gets its own hoist target.\n x <- lapply(args, r2f, scope, ...)\n code <- str_flatten_lines(x)\n\n # browser()\n value <- (if (length(args)) last(x)@value) %||% Variable()\n Fortran(code, value)\n}\n\n\n\n# ---- reduction intrinsics ----\n\n\ncreate_mask_hoist <- function() {\n .hoisted_mask <- NULL\n\n try_set <- function(mask) {\n stopifnot(inherits(mask, Fortran), mask@value@mode == \"logical\")\n # each hoist can only accept one mask.\n if (is.null(.hoisted_mask)) {\n .hoisted_mask <<- mask\n return(TRUE)\n }\n # if the mask is identical, we accept it.\n if (identical(.hoisted_mask, mask)) {\n return(TRUE)\n }\n # can't hoist this mask.\n FALSE\n }\n\n get_hoisted <- function() .hoisted_mask\n\n environment()\n}\n\n\nr2f_handlers[[\"max\"]] <-\nr2f_handlers[[\"min\"]] <-\nr2f_handlers[[\"sum\"]] <-\nr2f_handlers[[\"prod\"]] <- function(args, scope, ...) {\n intrinsic <- switch(last(list(...)$calls),\n max = \"maxval\",\n min = \"minval\",\n sum = \"sum\",\n prod = \"product\")\n\n reduce_arg <- function(arg) {\n mask_hoist <- create_mask_hoist()\n x <- r2f(arg, scope, ..., hoist_mask = mask_hoist$try_set)\n if(x@value@rank == 0)\n return(x)\n hoisted_mask <- mask_hoist$get_hoisted()\n s <- glue(\n if (is.null(hoisted_mask))\n \"{intrinsic}({x})\"\n else\n \"{intrinsic}({x}, mask = {hoisted_mask})\"\n )\n Fortran(s, Variable(x@value@mode))\n }\n\n if (length(args) == 1) {\n reduce_arg(args[[1]])\n } else {\n args <- lapply(args, reduce_arg)\n mode <- reduce_promoted_mode(args)\n s <- switch(last(list(...)$calls),\n max = glue(\"max({str_flatten_commas(args)})\"),\n min = glue(\"min({str_flatten_commas(args)})\"),\n sum = glue(\"({str_flatten(args, ' + ')})\"),\n prod = glue(\"({str_flatten(args, ' * ')})\")\n )\n Fortran(s, Variable(mode))\n }\n}\n\n\nr2f_handlers[[\"which.max\"]] <-\nr2f_handlers[[\"which.min\"]] <-\nfunction(args, scope = NULL, ...) {\n stopifnot(length(args) == 1)\n x <- r2f(args[[1L]], scope, ...)\n stopifnot(\"Values passed to which.max()/which.min() must be 1d arrays\" = x@value@rank == 1)\n valout <- Variable(mode = \"integer\") # integer scalar\n\n if (x@value@mode == \"logical\") {\n val <- switch(last(list(...)$calls),\n which.max = \".true.\",\n which.min = \".false.\")\n f <- glue(\"findloc({x}, {val}, 1)\")\n } else {\n intrinsic <- switch(last(list(...)$calls),\n which.max = \"maxloc\",\n which.min = \"minloc\")\n f <- glue(\"{intrinsic}({x}, 1)\")\n }\n\n Fortran(f, valout)\n}\n\n\nr2f_handlers[[\"[\"]] <- function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n\n # only a subset of R's x[...] features can be translated here. `...` can only be:\n # - a single logical mask, of the same rank as `x`. returns a rank 1 vector.\n # - a number of arguments matching the rank of `x`, with each being\n # an integer of rank 0 or 1. In this case, a rank 1 logical becomes\n # converted to an integer with\n\n var <- args[[1]]\n var <- r2f(var, scope, ...)\n\n idxs <- whole_doubles_to_ints(args[-1])\n idxs <- imap(idxs, function(idx, i) {\n if (is_missing(idx))\n Fortran(\":\", Variable(\"integer\", var@value@dims[[i]]))\n else\n r2f(idx, scope, ...)\n })\n\n if (length(idxs) == 1 &&\n idxs[[1]]@value@mode == \"logical\" &&\n idxs[[1]]@value@rank == var@value@rank) {\n mask <- idxs[[1]]\n if (hoist_mask(mask))\n return(var)\n return(Fortran(glue(\"pack({var}, {mask})\"), Variable(var@value@mode, dims = NA)))\n }\n\n if (length(idxs) != var@value@rank)\n stop(\"number of args to x[...] must match the rank of x, received:\",\n deparse1(as.call(c(quote(`[`,args )))))\n\n drop <- args$drop %||% TRUE\n\n idxs <- lapply(idxs, function(subscript) {\n # if (!idx@value@rank %in% 0:1)\n # stop(\"all args to x[...] must have rank 0 or 1\",\n # deparse1(as.call(c(quote(`[`,args )))))\n switch(\n paste0(subscript@value@mode, subscript@value@rank),\n logical0 = {\n Fortran(\":\", Variable(\"integer\", NA))\n },\n logical1 = {\n # we convert to a temp integer vector, doing the equivalent of R's which()\n i <- scope@get_unique_var(\"integer\")\n f <- glue(\"pack([({i}, {i}=1, size({subscript}))], {subscript})\")\n return(Fortran(f, Variable(\"int\", NA)))\n },\n integer0 = {\n if (drop)\n subscript\n else\n Fortran(glue(\"{subscript}:{subscript}\"), Variable(\"int\", 1))\n },\n integer1 = {\n subscript\n },\n # double0 = { },\n # double1 = { },\n stop(\n \"all args to x[...] must be logical or integer of rank 0 or 1\",\n deparse1(as.call(c(quote(`[`, args ))))\n )\n )\n })\n\n dims <- drop_nulls(lapply(idxs, \\(idx) idx@value@dims[[1]]))\n outval <- Variable(var@value@mode, dims)\n Fortran(glue(\"{var}({str_flatten_commas(idxs)})\"), outval)\n\n}\n\n\nr2f_handlers[[\":\"]] <- function(args, scope, ...) {\n # depending on context, this translation can vary.\n\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n args <- whole_doubles_to_ints(args)\n .[start, end] <- lapply(args, r2f, scope, ...)\n step <- glue(\"sign(1, {end}-{start})\")\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{start}:{end}:{step}\"),\n \"for\" = glue(\"{start}, {end}, {step}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {start}, {end}, {step}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\nr2f_handlers[[\"seq\"]] <- function(args, scope, ...) {\n args <- whole_doubles_to_ints(args) # only casts if trunc(dbl) == dbl\n if (!is.null(args$length.out) || !is.null(args$along.with)) {\n stop(\"seq(length.out=, along.with=) not implemented yet\")\n }\n\n\n .[from, to, by] <- lapply(args, r2f, scope, ...)[c(\"from\", \"to\", \"by\")]\n by <- by %||% Fortran(glue(\"sign(1, {to}-{from})\"), Variable(\"integer\"))\n\n # Fortran only supports integer sequences in do and implicit do contexts.\n # to make a double sequence, needs to be in via an implied map() call, like\n # seq(1, 10, .1) -> [(x * 0.1, x = 10, 50)]\n #\n # e.g., i <- scope@get_unique_var(\"integer\")\n # glue(\"[({i} * by, {i} = int(from/by), int(to/by))]\")\n if (from@value@mode != \"integer\" ||\n to@value@mode != \"integer\" ||\n by@value@mode != \"integer\")\n stop(\"non-integer seq()'s not implemented yet.\")\n\n # depending on context, this translation can vary.\n #\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{from}:{to}:{by}\"),\n \"for\" = glue(\"{from}, {to}, {by}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {from}, {to}, {by}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\n\n\nr2f_handlers[[\"ifelse\"]] <- function(args, scope, ...) {\n .[mask, tsource, fsource] <- lapply(args, r2f, scope, ...)\n # (tsource, fsource, mask)\n mode <- tsource@value@mode\n dims <- conform(mask@value, tsource@value, fsource@value)@dims\n Fortran(glue(\"merge({tsource}, {fsource}, {mask})\"),\n Variable(mode, dims))\n}\n\n\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- pure elemental unary math intrinsics ----\n\n## real and complex intrinsics\nr2f_handlers[[\"sin\"]] <-\nr2f_handlers[[\"cos\"]] <-\nr2f_handlers[[\"tan\"]] <-\nr2f_handlers[[\"asin\"]] <-\nr2f_handlers[[\"acos\"]] <-\nr2f_handlers[[\"atan\"]] <-\nr2f_handlers[[\"sqrt\"]] <-\nr2f_handlers[[\"exp\"]] <-\nr2f_handlers[[\"log\"]] <-\nr2f_handlers[[\"floor\"]] <-\nr2f_handlers[[\"ceiling\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n intrinsic <- last(list(...)$calls)\n Fortran(glue(\"{intrinsic}({arg})\"), arg@value)\n}\n\nr2f_handlers[[\"log10\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n f <- if(arg@value@mode == \"complex\") {\n glue(\"(log({arg}) / log(10.0_c_double))\")\n } else {\n glue(\"log10({arg})\")\n }\n Fortran(f, arg@value)\n}\n\n## accepts real, integer, or complex\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n if(arg@value@mode == \"complex\")\n arg@value@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- complex elemental unary intrinsics ----\n\nr2f_handlers[[\"Re\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"real({arg})\"), val)\n}\n\nr2f_handlers[[\"Im\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"aimag({arg})\"), val)\n}\n\n# Modulus (magnitude)\nr2f_handlers[[\"Mod\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), val)\n}\n\n# Argument (phase angle, radians)\nr2f_handlers[[\"Arg\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"atan2(aimag({arg}), real({arg}))\"), val)\n}\n\n# conjg() returns a complex value; R uses Conj()\nr2f_handlers[[\"Conj\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"complex\"\n Fortran(glue(\"conjg({arg})\"), val)\n}\n\n\n\n# ---- elemental binary infix operators ----\n\nr2f_handlers[[\"+\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} + {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"-\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} - {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"*\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} * {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"/\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} / {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"^\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} ** {right})\"), conform(left@value, right@value))\n}\n\n\nr2f_handlers[[\">=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} >= {right})\"), var)\n}\nr2f_handlers[[\">\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} > {right})\"), var)\n}\nr2f_handlers[[\"<\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} < {right})\"), var)\n}\nr2f_handlers[[\"<=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} <= {right})\"), var)\n}\nr2f_handlers[[\"==\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} == {right})\"), var)\n}\nr2f_handlers[[\"!=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} /= {right})\"), var)\n}\n\n\n\n# ---- remainder (%%) and integer division (%/%) ----\n#\n# R semantics:\n# x %% y == r where r has the sign of y (divisor)\n# x %/% y == q where q = floor(x / y)\n# and x == r + y * q (within rounding error)\n#\n# Fortran intrinsics:\n# - MODULO(a,p) : remainder with sign(p)\n# - FLOOR(x) : greatest integer ≤ x (real)\n# - AINT(x) : truncation toward 0 (real)\n\nr2f_handlers[[\"%%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n # MODULO gives result with sign(right) – matches R %% behaviour\n Fortran(glue(\"modulo({left}, {right})\"), out_val)\n}\n\nr2f_handlers[[\"%/%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n\n expr <- switch(\n out_val@mode,\n integer = glue(\"int(floor(real({left}) / real({right})))\"),\n double = glue(\"floor({left} / {right})\"),\n stop(\"%/% only implemented for numeric types\")\n )\n\n Fortran(expr, out_val)\n}\n\n\n\n# TODO: the scalar || probably need some more type checking.\n# TODO: gfortran supports implicit casting that of logical to integer when\n# assigning a logical to a variable declared integer, converting `.true.` to `1`,\n# but this is not a standard language feature, and Intel's `ifort` uses `-1` for `.true`.\n# We should explicitly use\n# `merge(1_c_int, 0_c_int, <lgl>)` to cast logical to int.\nr2f_handlers[[\"&\"]] <-\nr2f_handlers[[\"&&\"]] <-\nr2f_handlers[[\"|\"]] <-\nr2f_handlers[[\"||\"]] <-\nfunction(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n args <- lapply(args, function(a) {\n if (a@value@mode != \"logical\") {\n stop(\"must be logical\")\n }\n a\n })\n .[left, right] <- args\n\n operator <- switch(last(list(...)$calls),\n `&` = , `&&` = \".and.\",\n `|` = , `||` = \".or.\")\n\n s <- glue(\"{left} {operator} {right}\")\n val <- conform(left@value, right@value)\n val@mode <- \"logical\"\n Fortran(s, val)\n}\n\n\n\n\n# --- constructors ----\n\n\nr2f_handlers[[\"c\"]] <- function(args, scope = NULL, ...) {\n ff <- lapply(args, r2f, scope, ...)\n s <- glue(\"[ {str_flatten_commas(ff)} ]\")\n lens <- lapply(ff[order(map_int(ff, \\(f) f@value@rank))], function(e) {\n rank <- e@value@rank\n if (rank == 0)\n 1L\n else if (rank == 1)\n e@value@dims[[1]]\n else\n stop(\"all args passed to c() must be scalars or 1-d arrays\")\n })\n mode <- reduce_promoted_mode(ff)\n len <- Reduce(\\(l1, l2) {\n if (is_scalar_na(l1) || is_scalar_na(l2)) {\n NA\n } else if (is_wholenumber(l1) && is_wholenumber(l2)) {\n l1 + l2\n } else {\n call(\"+\", l1, l2)\n }\n }, lens)\n Fortran(s, Variable(mode, list(len)))\n}\n\n\nr2f_handlers[[\"cbind\"]] <- function(e, scope) {\n .NotYetImplemented()\n ee <- lapply(e[-1], r2f, scope)\n ncols <- lapply(ee, function(f) {\n if (f@value@rank %in% c(0, 1))\n 1\n else if (f@value@rank == 2)\n f@value@dims[[2]]\n })\n ncols <- Reduce(\\(a, b) call(\"+\", a, b), ncols)\n ncols <- eval(ncols, scope@sizes)\n}\n\n\n\nr2f_handlers[[\"<-\"]] <- function(args, scope, ...) {\n target <- args[[1]]\n if (is.call(target)) {\n # given a call like `foo(x) <- y`, dispatch to `foo<-`\n target_callable <- target[[1]]\n stopifnot(is.symbol(target_callable))\n name <- as.symbol(paste0(as.character(target_callable), \"<-\"))\n handler <- get_r2f_handler(name)\n return(handler(args, scope, ...)) # new hoist target\n }\n\n # It sure seems like it's be nice if the Fortran() constructor\n # took mode and dims as args directly,\n # without needing to go through Variable...\n stopifnot(is.symbol(target))\n name <- as.character(target)\n\n value <- args[[2]]\n value <- r2f(value, scope, ...)\n\n # immutable / copy-on-modify usage of Variable()\n if (is.null(var <- get0(name, scope))) {\n # this is a binding to a new symbol\n var <- value@value\n var@name <- name\n scope[[name]] <- var\n\n } else {\n # The var already exists, this assignment is a modification / reassignment\n check_assignment_compatible(var, value@value)\n var@modified <- TRUE\n # could probably drop this @modified property, and instead track\n # if the var populated by declare is identical at the end (e.g., perhaps by\n # address, or by attaching a unique id to each var, or ???)\n assign(name, var, scope)\n }\n\n Fortran(glue(\"{name} = {value}\"))\n}\n\n\nr2f_handlers[[\"[<-\"]] <- function(args, scope = NULL, ...) {\n\n # TODO: handle logical subsetting here, which must become a where a construct like:\n # x[lgl] <- val\n # becomes\n # where (lgl)\n # x = val\n # end where\n # ! but if {va} references {x}, it will only see the subset x, not the full {x}\n # e.g.,\n # sum(x) is not the same as `where lgl \\n sum(x) \\n end where`\n # ditto for ifelse() ?\n # e <- as.list(e)\n\n stopifnot(is_call(target <- args[[1L]], \"[\"))\n target <- r2f(target, scope)\n\n value <- r2f(args[[2L]], scope)\n Fortran(glue(\"{target} = {value}\"))\n}\n\nreduce_promoted_mode <- function(...) {\n\n getmode <- function(d) {\n if (inherits(d, Fortran))\n d <- d@value\n if (inherits(d, Variable))\n return(d@mode)\n if (is.list(d) && length(d))\n lapply(d, getmode)\n }\n modes <- unique(unlist(getmode(list(...))))\n\n if (\"double\" %in% modes)\n \"double\"\n else if (\"integer\" %in% modes)\n \"integer\"\n else if (\"logical\" %in% modes)\n \"logical\"\n else\n NULL\n\n}\n\n\nr2f_handlers[[\"=\"]] <- r2f_handlers[[\"<-\"]]\n\nr2f_handlers[[\"logical\"]] <- function(args, scope, ...) {\n Fortran(\".false.\", Variable(mode = \"logical\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"integer\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"integer\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"double\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"double\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"numeric\"]] <- r2f_handlers[[\"double\"]]\n\nr2f_handlers[[\"character\"]] <- r2f_handlers[[\"raw\"]] <-\n .r2f_handler_not_implemented_yet\n\n\nr2f_handlers[[\"matrix\"]] <- function(args, scope = NULL, ...) {\n\n args$data %||% stop(\"matrix(data=) must be provided, cannot be NA\")\n out <- r2f(args$data, scope, ...)\n out@value@dims <- r2dims(list(args$nrow, args$ncol), scope)\n out\n\n # TODO: reshape() if !passes_as_scalar(out)\n}\n\n\n\nconform <- function(..., mode = NULL) {\n var <- NULL\n # technically, types are implicit promoted, but we'll let <- handle that.\n for (var in drop_nulls(list(...))) {\n if (passes_as_scalar(var)) {\n next\n } else {\n break\n }\n }\n if (is.null(var))\n NULL\n else\n Variable(mode %||% var@mode, var@dims)\n }\n\n\n\n# ---- printers ----\n\n\nr2f_handlers[[\"cat\"]] <- function(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n # can do a lot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"character\")\n label <- args[[1]]\n if (!endsWith(label, \"\\n\"))\n stop(\"cat(<strings>) must end with '\\n'\")\n label <- substring(label, 1, nchar(label)-1)\n\n Fortran(glue('call labelpr(\"{label}\", {nchar(label)})'))\n}\n\nr2f_handlers[[\"print\"]] <- function(args, scope = NULL, ...) {\n # args <- lapply(as.list(e)[-1], r2f, scope)\n # args <- as.list(e)[-1]\n # can do alot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"symbol\")\n name <- args[[1]]\n var <- get(name, envir = scope)\n name <- as.character(name)\n if (var@mode == \"logical\")\n name <- sprintf(\"(%s/=0)\", name)\n label <- \"\"\n # browser()\n if (passes_as_scalar(var)) {\n # } \"scalar\"\n # paste0(c(var@mode, scalar) collapse = \"_\"),\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr1\",\n double = \"dblepr1\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name})'))\n } else {\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr\",\n double = \"dblepr\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name}, size({name}))'))\n }\n}\n\n# r2f_handlers[[\"ifelse\"]] <- function(e, scope) {\n# # TODO:\n# # <- and [<- need to be aware of this construct for it to make sense.\n# .[test, yes, no] <- lapply(e[-1], r2f, scope)\n# Fortran(glue(\"where ({test}}\n# {indent(yes)}\n# elsewhere\n# {indent({no})\n# end where\"))\n# }\n\n\nr2f_handlers[[\"length\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x})\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"nrow\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 1)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"ncol\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 2)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"dim\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"shape({x})\"), Variable(\"integer\", x@value@rank))\n}\n\n\n\n\n# this is just `[` handler\nr2f_slice <- function(args, scope, ...) { }\n\n\n\n# ---- control flow ----\n\n\nr2f_handlers[[\"if\"]] <- function(args, scope, ..., hoist = NULL) {\n # cond uses the current hoist context.\n cond <- r2f(args[[1]], scope, ..., hoist = hoist)\n\n # true and false branchs gets their own hoist target.\n true <- r2f(args[[2]], scope, ..., hoist = NULL)\n\n if (length(args) == 2) {\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n end if\n \"))\n } else {\n false <- r2f(args[[3]], scope, ..., hoist = NULL)\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n else\n {indent(false)}\n end if\n \"))\n }\n}\n\n\n# TODO: return\n\n# ---- repeat ----\nr2f_handlers[[\"repeat\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n body <- r2f(args[[1]], scope, ...)\n Fortran(glue(\n \"do\n {indent(body)}\n end do\n \"))\n}\n\n# ---- break ----\nr2f_handlers[[\"break\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"exit\")\n}\n\n# ---- break ----\nr2f_handlers[[\"next\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"cycle\")\n}\n\n# ---- while ----\nr2f_handlers[[\"while\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 2L)\n cond <- r2f(args[[1]], scope, ...)\n body <- r2f(args[[2]], scope, ...) ## should we set a new hoist target here?\n Fortran(glue(\n \"do while ({cond})\n {indent(body)}\n end do\n \"))\n}\n\n## ---- for ----\nr2f_iterable <- function(e, scope, ...) {\n .NotYetImplemented()\n\n if (is.symbol(e)) {\n var <- get(e, scope)\n iterable <- r2f(...)\n }\n\n # list(var, iterable, body_prefix)\n}\n\n\n\n\nr2f_handlers[[\"for\"]] <- function(args, scope, ...) {\n .[var, iterable, body] <- args\n stopifnot(is.symbol(var))\n var <- as.character(var)\n scope[[var]] <- Variable(mode = \"integer\", name = var)\n\n iterable <- r2f_iterable_handlers[[as.character(iterable[[1]])]](iterable, scope)\n body <- r2f(body, scope, ...)\n\n Fortran(glue(\n \"do {var} = {iterable}\n {indent(body)}\n end do\n \"))\n}\n\nr2f_iterable_handlers := new.env()\n\nr2f_iterable_handlers[[\"seq_len\"]] <- function(e, scope, ...) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_len()\")\n x <- x[[1]]\n start <- 1L\n end <- r2f(x)\n glue(\"{start}, {end}\")\n}\n\nr2f_iterable_handlers[[\"seq\"]] <- function(e, scope) {\n\n ee <- match.call(seq.default, e)\n ee <- whole_doubles_to_ints(ee)\n\n start <- r2f(ee$from, scope)\n end <- r2f(ee$to, scope)\n step <- if (is.null(ee$by))\n glue(\"sign(1, {end}-{start})\")\n else\n r2f(ee$by, scope)\n\n str_flatten_commas(\n start, end, step\n )\n}\n\nr2f_iterable_handlers[[\":\"]] <- function(e, scope) {\n\n ee <- whole_doubles_to_ints(e)\n .[start, end] <- as.list(ee)[-1] |> lapply(r2f, scope)\n\n glue(\"{start}, {end}, sign(1, {end}-{start})\")\n}\n\n\n\nr2f_iterable_handlers[[\"seq_along\"]] <- function(e, scope) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_along()\")\n x <- x[[1]]\n start <- 1\n end <- sprintf(\"size(%s)\", r2f(x, scope))\n glue(\"{start}, {end}\")\n}\n\n\n# ---- helpers ----\n\ncheck_call <- function(e, nargs) {\n if (length(e) != (nargs+1L))\n stop(\"Too many args to: \", as.character(e[[1L]]))\n}\n"], ["/quickr/R/manifest.R", "\n\n\n### local variables with unspecified size are 'allocatable'. If they are bound\n### to a named symbol, the manifest must mark it as allocatable.\n###\n### Generally, if an expression produces an array of unspecified size, even if\n### it's never bound, it's still 'allocatable'. For example, an inline fortran\n### `pack()` call likely still produces a corresponding `malloc()` in the\n### generated code, regardless of if the output of `pack()` is bound to\n### a symbol (in the case of pack specifically, the malloc is behind a\n### _gfortran_pack() call.\n###\n### We can potentially link/mask `_malloc` and `_free` with a custom one that\n### uses R_alloc(), which will automatically free after the .External() call\n### returns. We can also pass along -fstack-arrays to gfortran and flang-new\n### (llvm), and that will mostly get rid most of the malloc calls, instead\n### allocating arrays on the C stack (which will automatically free on\n### return/lngjmp), but that will run into issues with larger arrays (especially\n### on windows)\n###\n### local vars of undefined sizes are allocatable. These will typically be\n### allocated on the c stack if they are not too large, but may include a\n### malloc+free call if they are large. Those might leak if we lngjmp\n### away (e.g., due to an interrupt). This potential leak is a non-issue for\n### now, since interrupts aren't supported yet, so there is no risk of lngjmp.\n###\n### When we do add support for interruptable quick functions, this potential\n### leak could be guarded against by:\n###\n### a) linking malloc -> R_alloc() for the fortran compilation unit which\n### would make the memory automatically be released after .External()\n### return. Note that unlinke malloc(), R_alloc() is not thread safe, so we would need\n### additional work for a `do concurrent` context to be supported.\n###\n### b) forcing all arrays to be stack allocated with -fstack-arrays passed\n### to the gfortran/flang-new. This is not a great, since c stack limits are\n### typically \"small\" and enforced by the OS.\n\nr2f.scope <- function(scope) {\n\n vars <- as.list.environment(scope, all.names = TRUE)\n vars <- lapply(vars, function(var) {\n\n intent_in <- var@name %in% names(formals(scope@closure))\n intent_out <- var@name == closure_return_var_name(scope@closure) || intent_in && var@modified\n\n intent <-\n if (intent_in && intent_out) \"intent(in out)\"\n else if (intent_in) \"intent(in)\"\n else if (intent_out) \"intent(out)\"\n else NULL\n\n type <- switch(var@mode,\n double = \"real(c_double)\",\n integer = \"integer(c_int)\",\n complex = \"complex(c_double_complex)\",\n logical = if (intent_in || intent_out) \"integer(c_int)\" else \"logical\",\n raw = \"integer(c_int8_t)\",\n stop(\"unrecognized kind: \", format(var))\n )\n\n dims <- if (passes_as_scalar(var)) {\n NULL\n } else {\n dims2f(var@dims, scope) |> str_flatten_commas() |> sprintf(fmt = \"(%s)\")\n }\n\n allocatable <- if (!is.null(dims) && grepl(\":\", dims, fixed = TRUE))\n \"allocatable\"\n\n if (intent_in && intent_out && !is.null(allocatable))\n stop(\"all input and output vars must have a fully defined shape\")\n\n name <- var@name\n comment <- if (var@mode == \"logical\") \" ! logical\"\n\n glue('{str_flatten_commas(type, intent, allocatable)} :: {name}{dims}{comment}',\n .null = \"\")\n })\n\n # vars that will be visible in the C bridge, either as an input or output\n non_local_var_names <- unique(c(names(formals(scope@closure)),\n closure_return_var_name(scope@closure)))\n\n # collect all size_names; sort so non-locals are declared first.\n size_names <- unique(unlist(lapply(non_local_var_names, function(name) {\n var <- scope[[name]]\n lapply(var@dims, all.names, functions = FALSE, unique = TRUE)\n }))) |> setdiff(names(formals(scope@closure)))\n\n sizes <- lapply(size_names, function(name) {\n kind <- if (endsWith(name, \"_len_\")) \"c_ptrdiff_t\" else \"c_int\"\n glue(\"integer({kind}), intent(in), value :: {name}\")\n })\n\n manifest <- compact(list(\n sizes = sizes,\n args = vars[non_local_var_names],\n locals = vars[setdiff(names(vars), non_local_var_names)]\n ))\n\n manifest <- imap(manifest, \\(declarations, category)\n str_flatten_lines(paste(\"!\", category), declarations)) |>\n str_flatten(\"\\n\\n\")\n\n manifest <- str_flatten_lines(\"! manifest start\", manifest, \"! manifest end\")\n\n # symbols that must come in as args to the subroutine\n # # method=\"radix\" for locale-independent stable order.\n signature <- unique(c(non_local_var_names, sort(size_names, method = \"radix\")))\n attr(manifest, \"signature\") <- signature\n\n manifest\n}\n\n\n\n## fortran precedence order\n## ** (exp)\n## * /\n## + -\n##\n## R prededence order\n## ^\n## - +\n## %/% %%\n## * /\n\n## generally, we just deparse() to convert an axis size.\n## except for NA, which becomes \":\"\n\ndims2f_eval_base_env <- new.env(parent = emptyenv())\ndims2f_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\n\n# any call always evaluates to a string.\n# every argument will be either:\n# - NA -> translates to \":\"\n# - a symbol -> translates to deparsed string\n# - a call ->\n\ndims2f_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2f_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2f_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2f_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"real({e1}) / real({e2})\")\n# dividing integers truncates towards 0\ndims2f_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"int({e1}) / int({e2})\")\ndims2f_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"mod(int({e1}), int({e2}))\")\ndims2f_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1})**({e2})\")\n\n\ndims2f <- function(dims, scope) {\n syms <- unique(unlist(lapply(dims, \\(d) if (is.language(d)) all.vars(d))))\n vars <- as.list(syms)\n names(vars) <- syms\n eval_env <- list2env(vars, parent = dims2f_eval_base_env)\n dims <- map_chr(dims, function(d) {\n d <- eval(d, eval_env)\n if (is.symbol(d)) as.character(d)\n else if (is_wholenumber(d)) as.character(d)\n else if (is_scalar_na(d)) \":\"\n else if (is_string(d)) d\n else if (inherits(d, Variable)) {\n # a locally allocated var that is a return var\n if (!d@modified && d@is_arg)\n return(d@name)\n stop(\"unexpected axis size value\")\n }\n })\n if (!length(dims) || identical(dims, \"1\")) \"\"\n else str_flatten_commas(dims)\n}\n\n"], ["/quickr/R/subroutine.R", "\n\nnew_fortran_subroutine <- function(name, closure, parent = emptyenv()) {\n\n\n check_all_var_names_valid(closure)\n\n # translate body, and populate scope with variables\n body <- body(closure)\n\n # defuse calls like `-1` and `1+1i`. Not really necessary, but simplifies downstream a little.\n body <- defuse_numeric_literals(body)\n\n # TODO: try harder here to use one of the input vars as the output var\n body <- ensure_last_expr_sym(body)\n\n # update closure with sym return value\n base::body(closure) <- body\n # body <- rlang::zap_srcref(body)\n\n scope <- new_scope(closure, parent)\n\n # inject symbols for var sizes in declare calls, so like:\n # declare(type(foo = integer(nr, NA)),\n # type(bar = integer(nr, 3)))\n # become:\n # declare(type(foo = integer(foo_dim_1_, foo_dim_2_)),\n # type(bar = integer(foo_dim_1_, 3L)))\n body <- substitute_declared_sizes(body)\n body <- r2f(drop_last(body), scope)\n\n # check all input vars were declared\n # TODO: this check might be too late, because r2f() might throw cryptic errors\n # when handling undeclared variables. Either throw better errors from r2f(), or\n # handle all declares first\n for(arg_name in names(formals(closure))) {\n if (is.null(var <- get0(arg_name, scope)))\n stop(\"arg not declared: \", arg_name)\n }\n\n # figure out the return variable.\n if (is.symbol(last_expr <- last(body(closure)))) {\n return_var <- get(last_expr, scope)\n return_var@is_return <- TRUE\n scope[[as.character(last_expr)]] <- return_var\n } else {\n # lots we can still do here, just not implemented yet.\n stop(\"last expression in the function must be a bare symbol\")\n }\n\n manifest <- r2f.scope(scope)\n fsub_arg_names <- attr(manifest, \"signature\", TRUE)\n\n used_iso_bindings <- unique(unlist(use.names = FALSE, list(\n lapply(scope, function(var) {\n list(\n switch(\n var@mode,\n double = \"c_double\",\n integer = \"c_int\",\n logical = if (var@name %in% fsub_arg_names)\n \"c_int\",\n complex = \"c_double_complex\",\n raw = \"c_int8_t\"\n ),\n lapply(var@dims, function(size) {\n syms <- all.vars(size)\n c(if (any(grepl(\"__len_$\", syms))) \"c_ptrdiff_t\",\n if (any(grepl(\"__dim_[0-9]+_$\", syms))) \"c_int\")\n })\n )\n }))))\n\n # check for literal kinds\n if (!\"c_int\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+_c_int\\\\b\", body))\n append(used_iso_bindings) <- \"c_int\"\n }\n if (!\"c_double\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+\\\\.[0-9]+_c_double\\\\b\", body))\n append(used_iso_bindings) <- \"c_double\"\n }\n used_iso_bindings <- sort(used_iso_bindings, method = \"radix\")\n\n subroutine <- glue(\"\n subroutine {name}({str_flatten_commas(fsub_arg_names)}) bind(c)\n use iso_c_binding, only: {str_flatten_commas(used_iso_bindings)}\n implicit none\n\n {indent(manifest)}\n\n {indent(body)}\n end subroutine\n \")\n\n subroutine <- insert_fortran_line_continuations(subroutine)\n\n FortranSubroutine(\n subroutine,\n name = name,\n signature = fsub_arg_names,\n scope = scope,\n closure = closure\n )\n}\n\ninsert_fortran_line_continuations <- function(code, preserve_attributes = TRUE) {\n attrs_in <- attributes(code)\n\n code <- as.character(code)\n lines <- str_split_lines(code)\n lines <- trimws(lines, \"right\")\n\n if (any(too_long <- nchar(lines) > 132)) {\n # remove leading indentation\n lines[too_long] <- trimws(lines[too_long], \"left\")\n\n # move trailing comment at the end\n lines[too_long] <- sub(\"^(.*)!(.*)$\", \"!\\\\2\\n\\\\1\", lines[too_long])\n lines <- str_split_lines(lines)\n\n # maximum 255 continuations are allowed\n for (i in 1:256) {\n if (!any(too_long <- nchar(lines) > 132))\n break\n lines[too_long] <- sub(\"^(.{1,130})\\\\s\", \"\\\\1 &\\n\", lines[too_long])\n lines <- str_split_lines(lines)\n }\n if (i > 255L)\n stop(\"Too long line encountered. Please split long expressions into a sequence of smaller expressions.\")\n }\n\n code <- str_flatten_lines(lines)\n if (preserve_attributes)\n attributes(code) <- attrs_in\n code\n}\n\n"], ["/quickr/R/sizes.R", "\n\n\ncheck_type_call <- function(cl) {\n if (length(cl) > 2)\n stop(\"only one variable can be declared per type() call\")\n args <- as.list(cl)[-1]\n if (length(names(args)) != 1)\n stop(\"name must be provided as: type(<name> = <mode>(<<dims>>)\")\n if (!is.call(args[[1]]) && as.character(args[[1]]) %in% .atomic_type_names)\n stop(\"only atomic modes are supported\")\n}\n\n\ntype_call_to_var <- function(cl) {\n check_type_call(cl)\n Variable(\n name = names(cl)[-1],\n mode = as.character(cl[[2L]][[1L]]),\n dims = unname(as.list(cl[[2]])[-1])\n )\n}\n\nvar_to_type_call <- function(var) {\n arg <- as.call(c(as.symbol(var@mode), var@dims))\n arg <- setNames(list(arg), var@name)\n as.call(c(quote(type), arg))\n}\n\n\nget_flattened_args <- function(cl) {\n # flatten exprs from `{` in usage like declare({ ... })`\n args <- as.list(cl)[-1]\n args <- lapply(args, function(e) {\n if (is_missing(e))\n NULL\n else if (is_call(e, quote(`{`)))\n get_flattened_args(e)\n else\n list(e)\n })\n unlist(args, recursive = FALSE)\n}\n\nself_evaluate <- function(...) sys.call()\n\nsubstitute_declared_sizes <- function(e) {\n stopifnot(is_call(e, quote(`{`)))\n\n aliases <- new.env(parent = emptyenv())\n eval_env <- new.env(parent = emptyenv())\n for(name in all.names(e, functions = TRUE, unique = TRUE))\n assign(name, self_evaluate, eval_env)\n eval_env <- new.env(parent = eval_env)\n for(name in all.names(e, functions = FALSE, unique = TRUE))\n assign(name, as.symbol(name), eval_env)\n\n eval_env$`{` <- function(...) {\n as.call(c(list(quote(`{`)), list(...)))\n }\n\n eval_env$declare <- function(...) {\n args <- get_flattened_args(sys.call())\n args <- lapply(args, function(e) {\n if (is_type_call(e)) {\n var <- type_call_to_var(e)\n var@dims <- imap(var@dims, function(size, axis) {\n size_name <- as.symbol(get_size_name(var, axis))\n if (is.symbol(size) && !exists(size, aliases)) {\n # user defined implicit size_name alias\n assign(as.character(size), size_name, aliases)\n size <- size_name\n } else if (is_scalar_na(size)) {\n size <- size_name\n } else if (is_wholenumber(size)) {\n size <- as.integer(size)\n }\n size\n })\n e <- var_to_type_call(var)\n }\n e\n })\n\n as.call(c(quote(declare), args))\n }\n\n e <- eval(e, eval_env)\n\n # Now the 'aliases' env is populated; go through and substitute\n # size aliases with the actual size name.\n eval_env$declare <- function(...) {\n as.call(lapply(sys.call(), function(e) {\n if (is_type_call(e))\n e <- substitute_(e, aliases)\n e\n }))\n }\n\n eval(e, eval_env)\n\n}\n\n\nr2size <- function(r, scope) {\n typeof(r) |> switch(\n integer = r,\n double = {\n if (is_wholenumber(r))\n as.integer(r)\n else\n stop(\"size must be an integer, found: \", r)\n },\n symbol = {\n if (is_size_name(r))\n return(r)\n var <- get(r, scope)\n if (var@mode != \"integer\" || !passes_as_scalar(var))\n warning(\"size is not an integer:\", as.character(r))\n if (var@is_arg && !var@modified)\n return(r)\n # TODO: add specific unit tests here\n if (identical(var@r, r))\n return(r)\n # make a best effort to use the r expression last assigned to the\n # symbol, or fail gracefully and return NA.\n # closure-locals with unspecified shape are declared allocatable\n # input and/or output args with unspecified shape signal an error.\n r2size(var@r, scope)\n },\n language = {\n as.character(r[[1]]) |> switch(\n `+` = , `-` = , `/` = , `*` = , `^` = , `%/%` = , `%%` = {\n args <- as.list(r)[-1]\n args <- lapply(args, r2size, scope)\n if (anyNA(rapply(args, as.list)))\n return(NA_integer_)\n cl <- as.call(c(r[[1]], args))\n if (all(map_lgl(args, is.atomic)))\n cl <- eval(cl, baseenv())\n cl\n },\n length = {\n var <- get(r[[2L]], scope)\n if (var@rank == 1)\n return(var@dims[[1L]])\n len <- reduce(var@dims, \\(d1, d2) call(\"*\", d1, d2))\n r2size(len, scope)\n },\n `[` = {\n # [ only works when paired with dim()\n if (!is_call(r[[2L]], quote(dim)))\n return(NA_integer_)\n var <- get(r[[2L]][[2L]], scope)\n axis <- r[[3]]\n if (!is_wholenumber(axis))\n return(NA_integer_)\n if (axis > var@rank)\n stop(\"insufficient rank of variable in \", deparse1(r))\n var@dims[[axis]]\n },\n # dim = {\n #\n # },\n nrow = {\n var <- get(r[[2L]], scope)\n var@dims[[1]]\n },\n ncol = {\n var <- get(r[[2L]], scope)\n var@dims[[2]]\n },\n NA_integer_)\n },\n NA_integer_\n )\n}\n\nr2dims <- function(r, scope) {\n if (is.call(r)) {\n as.character(r[[1]]) |> switch(\n dim = {\n var <- get(r[[2L]], scope)\n return(var@dims)\n },\n c = {\n args <- lapply(r[-1], r2dims, scope)\n dims <- unlist(args, recursive = FALSE)\n return(as.list(dims))\n },\n r <- list(r))\n }\n lapply(r, r2size, scope)\n}\n\nget_size_name <- function(var, axis = NULL, name = var@name, rank = var@rank) {\n stopifnot(is.null(axis) || is_wholenumber(axis) && axis > 0)\n if (is.null(axis) || rank == 1 && axis == 1)\n sprintf(\"%s__len_\", name)\n else {\n if (axis > rank) stop(\"axis must not be > rank\")\n sprintf(\"%s__dim_%i_\", name, axis)\n }\n}\n\n\n\n# TODO: allow syntax like:\n# declare(type(a, b, c = integer(1)))\n# or:\n# declare(type(a = , b = , c = integer(1)))\n"], ["/quickr/R/compile-package.R", "\n\n\n#' Compile all `quick()` functions in a package.\n#'\n#' This will compile all `quick()` functions in an R package, and\n#' generate source files in the `src/` directory.\n#'\n#' Note, this function is automatically invoked during a `pkgload::load_all()` call.\n#'\n#' @param path Path to an R package\n#'\n#' @returns Called for its side effect.\n#' @export\ncompile_package <- function(path = \".\") {\n if (path != \".\") {\n owd <- setwd(path)\n on.exit(setwd(owd), add = TRUE)\n }\n\n if (!dir.exists(\"R\") || !file.exists(\"DESCRIPTION\"))\n stop(path, \" does not appear to be an R package.\")\n\n pkgname <- read.dcf(\"DESCRIPTION\", \"Package\")\n if (length(pkgname) != 1)\n stop(sprintf(\"path '%s' does not point to an R package\", path))\n pkgname <- as.character(pkgname)\n\n # collect all `quick()` calls in the package\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n\n # TODO: need to unset various R_* env vars, or just\n # take a dep on callr\n system2(file.path(R.home(\"bin\"), \"R\"),\n c(\"-q\", \"-e\", shQuote(\"pkgload::load_all()\")))\n}\n\n\ndump_collected <- function() {\n\n collected <- collector$get_collected()\n\n # try to resolve closure names for anonymous functions\n pkg_ns <- topenv(environment(collected[[1L]]$closure))\n pkg_funcs <- as.list.environment(pkg_ns, all.names = TRUE)\n tab <- hashtab(\"address\", length(collected))\n for (i in seq_along(pkg_funcs)) {\n if (typeof(fn <- pkg_funcs[[i]]) == \"closure\")\n # if is quick closure ...\n sethash(tab, pkg_funcs[[i]], names(pkg_funcs)[i])\n }\n\n quick_funcs <- unlist(recursive = FALSE, lapply(collected, function(x) {\n if (!startsWith(x$name, \"anonymous_quick_function_\"))\n return(setNames(list(x$closure), x$name))\n true_name <- gethash(tab, x$quick_closure)\n if (is.null(true_name))\n return(setNames(list(x$closure), x$name))\n # update pkg_ns with true name\n quick_closure <- create_quick_closure(true_name, x$closure)\n pkg_ns[[true_name]] <- quick_closure\n remhash(tab, x$quick_closure)\n setNames(list(x$closure), true_name)\n }))\n\n\n pkgname <- basename(normalizePath(\".\"))\n\n # check if we have a useDynLib line in NAMESPACE.\n if (!any(sapply(parse(file = \"NAMESPACE\"), function(e) {\n identical(e[[1]], quote(useDynLib)) && isTRUE(e$.registration)\n })))\n message(\"- Please add this roxygen directive somewhere in the Package R sources:\\n \",\n glue(\"#' @useDynLib {pkgname}, .registration = TRUE\"), \"\\n\",\n \"- Then run `devtools::document()`\\n\")\n\n sources <- zip_lists(imap(quick_funcs, function(func, name) {\n fsub <- new_fortran_subroutine(name, func)\n cbridge <- make_c_bridge(fsub, headers = name == names(quick_funcs)[1])\n list(f90 = fsub, c = cbridge)\n })) |> lapply(\\(x) x |> unlist() |> interleave(\"\\n\"))\n\n entries <- paste0(sprintf(' {\"%1$s\", (DL_FUNC) &%1$s, -1}',\n paste0(names(quick_funcs), \"_\")),\n collapse = \",\\n\")\n entries <- sprintf(\"static const R_ExternalMethodDef QuickrEntries[] = {\\n%s\\n};\",\n entries)\n\n append(sources$c) <- c(\"\", entries, \"\")\n\n R_init_pkg <- paste0(\"R_init_\", pkgname, \"(\")\n has_pkg_init_fn <- list.files(\"src\", pattern = \"\\\\.(c|cpp|h|hpp|c\\\\+\\\\+)$\",\n recursive = TRUE, all.files = TRUE,\n full.names = TRUE) |>\n setdiff(\"src/quickr_entrypoints.c\") |>\n lapply(function(f) {\n any(grepl(R_init_pkg, readLines(f, warn = FALSE), fixed = TRUE))\n }) |> unlist() |> any()\n\n append(sources$c) <- c(\"#include <R_ext/Rdynload.h>\", \"\")\n\n init_fn <- if (has_pkg_init_fn) {\n glue(\"\n void R_init_{pkgname}_quick_functions(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n }}\")\n } else {\n init_pkgname <- gsub(\".\", \"_\", pkgname, fixed = TRUE)\n glue(\"\n void R_init_{init_pkgname}(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n R_useDynamicSymbols(dll, FALSE);\n }}\")\n }\n\n append(sources$c) <- init_fn\n\n sources <- lapply(sources, str_split_lines)\n\n src_files_written <- FALSE\n if (!file.exists(\"src\")) dir.create(\"src\")\n cbridges_filepath <- \"src/quickr_entrypoints.c\"\n if (!file.exists(cbridges_filepath) || !identical(sources$c, readLines(cbridges_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(cbridges_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$c, cbridges_filepath)\n cli::cli_inform(c(i = \"Updated {.file {cbridges_filepath}}\"))\n src_files_written <- TRUE\n }\n\n fsubs_filepath <- \"src/quickr_sub_routines.f90\"\n if (!file.exists(fsubs_filepath) || !identical(sources$f90, readLines(fsubs_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(fsubs_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$f90, fsubs_filepath)\n cli::cli_inform(c(i = \"Updated {.file {fsubs_filepath}}\"))\n src_files_written <- TRUE\n }\n\n if (src_files_written) {\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_all)) {\n defer(pkgload::load_all(), sys.frame(i), after = TRUE)\n rlang::return_from(sys.frame(i), value = invisible())\n break\n }\n }\n }\n invisible()\n}\n\npkg_dll_path <- function (pkgname) {\n file.path(\"src\", paste0(pkgname, .Platform$dynlib.ext))\n}\n\n\ncollector <- local({\n\n .collected <- NULL\n\n activate <- function(name = NULL) {\n .collected <<- list()\n attr(.collected, \"name\") <<- name\n }\n\n is_active <- function() {\n is.list(.collected)\n }\n\n add <- function(...) {\n .collected[[length(.collected)+1L]] <<- list(...)\n }\n\n get_collected <- function(clear = TRUE) {\n if (clear)\n on.exit(.collected <<- NULL)\n .collected\n }\n\n environment()\n})\n"], ["/quickr/R/quick.R", "#' Compile a Quick Function\n#'\n#' Compile an R function.\n#'\n#' @param fun An R function\n#' @param name Optional string, name to use for the function.\n#'\n#' @details\n#'\n#' ## `declare(type())` syntax:\n#'\n#' The shape and mode of all function arguments must be declared. Local and\n#' return variables may optionally also be declared.\n#'\n#' `declare(type())` also has support for declaring size constraints, or size\n#' relationships between variables. Here are some examples of declare calls:\n#'\n#' ```r\n#' declare(type(x = double(NA))) # x is a 1-d double vector of any length\n#' declare(type(x = double(10))) # x is a 1-d double vector of length 10\n#' declare(type(x = double(1))) # x is a scalar double\n#'\n#' declare(type(x = integer(2, 3))) # x is a 2-d integer matrix with dim (2, 3)\n#' declare(type(x = integer(NA, 3))) # x is a 2-d integer matrix with dim (<any>, 3)\n#'\n#' # x is a 4-d logical matrix with dim (<any>, 24, 24, 3)\n#' declare(type(x = logical(NA, 24, 24, 3)))\n#'\n#' # x and y are 1-d double vectors of any length\n#' declare(type(x = double(NA)),\n#' type(y = double(NA)))\n#'\n#' # x and y are 1-d double vectors of the same length\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' # x and y are 1-d double vectors, where length(y) == length(x) + 2\n#' declare(type(x = double(n)),\n#' type(y = double(n+2)))\n#' ```\n#'\n#' You can provide declarations to `declare()` as:\n#'\n#' - Multiple arguments to a single `declare()` call\n#' - Separate `declare()` calls\n#' - Multiple arguments within a code block (`{}`) inside `declare()`\n#'\n#' ```r\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' declare(type(x = double(n)))\n#' declare(type(y = double(n)))\n#'\n#' declare({\n#' type(x = double(n))\n#' type(y = double(n))\n#' })\n#' ```\n#'\n#' ## Return values\n#'\n#' The shape and type of a function return value must be known at compile time.\n#' In most situations, this will be automatically inferred by `quick()`. However,\n#' if the output is dynamic, then you may need to provide a hint.\n#' For example, returning the result of `seq()` will fail because the output shape\n#' cannot be inferred.\n#'\n#' ```r\n#' # Will fail to compile:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' ```\n#'\n#' However, if the output size can be declared as a dynamic expression using other\n#' values known at runtime, compilation will succeed:\n#'\n#' ```r\n#' # Succeeds:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' type(out = integer(end - start + 1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' quick_seq(1L, 5L)\n#' ```\n#'\n#' @returns A quicker R function.\n#' @export\n#' @examples\n#' add_ab <- quick(function(a, b) {\n#' declare(type(a = double(n)),\n#' type(b = double(n)))\n#' out <- a + b\n#' out\n#' })\n#' add_ab(1, 2)\nquick <- function(fun, name = NULL) {\n if (is.null(name)) {\n name <- if (is.symbol(substitute(fun)))\n deparse(substitute(fun))\n else\n make_unique_name(prefix = \"anonymous_quick_function_\")\n }\n\n if (nzchar(pkgname <- Sys.getenv(\"DEVTOOLS_LOAD\"))) {\n if (!collector$is_active()) {\n if (!requireNamespace(\"pkgload\", quietly = TRUE)) {\n stop(\"Please install 'pkgload'\")\n }\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_code)) {\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n defer(dump_collected(), sys.frame(i), after = TRUE)\n break\n }\n }\n }\n }\n\n if (collector$is_active()) {\n # we are in a quickr::compile_package() or a devtools::load_all() call,\n # merely collecting functions at this point.\n quick_closure <- create_quick_closure(name, fun)\n collector$add(name = name, closure = fun, quick_closure = quick_closure)\n return(quick_closure)\n }\n\n pkgname <- parent.pkg()\n if (!is.null(pkgname) && pkgname != \"quickr\") {\n # we are in a package - but outside a quickr::compile_package() call.\n return(create_quick_closure(name, fun))\n }\n\n # not in a package. Compile and load eagerly.\n attr(fun, \"name\") <- name\n fun <- compile(r2f(fun))\n attr(fun, \"name\") <- NULL\n\n fun\n}\n\ncompile <- function(fsub, build_dir = tempfile(paste0(fsub@name, \"-build-\"))) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n name <- fsub@name\n c_wrapper <- make_c_bridge(fsub)\n\n if (dir.exists(build_dir)) unlink(build_dir, recursive = T)\n if (!dir.exists(build_dir))\n dir.create(build_dir)\n owd <- setwd(build_dir)\n on.exit(setwd(owd))\n\n fsub_path <- paste0(name, \"_fsub.f90\")\n c_wrapper_path <- paste0(name, \"_c_wrapper.c\")\n dll_path <- paste0(name, .Platform$dynlib.ext)\n writeLines(fsub, fsub_path)\n writeLines(c_wrapper, c_wrapper_path)\n\n suppressWarnings({\n result <- system2(\n R.home(\"bin/R\"),\n c(\"CMD SHLIB --use-LTO\", \"-o\", dll_path, fsub_path, c_wrapper_path),\n stdout = TRUE, stderr = TRUE\n )\n })\n if (!is.null(attr(result, \"status\"))) {\n writeLines(result, stderr())\n str(attributes(result))\n stop(\"Compilation Error\")\n }\n\n # tryCatch(dyn.unload(dll_path), error = identity)\n dll <- dyn.load(dll_path)\n c_wrapper_name <- paste0(fsub@name, \"_\")\n ptr <- getNativeSymbolInfo(c_wrapper_name, dll)$address\n\n create_quick_closure(fsub@name, fsub@closure, native_symbol = ptr)\n}\n\n\n\ncreate_quick_closure <- function(name, closure,\n native_symbol = as.name(paste0(name, \"_\"))) {\n body(closure) <- as.call(c(quote(.External), native_symbol,\n lapply(names(formals(closure)), as.name)))\n closure\n}\n\n\n\ncheck_all_var_names_valid <- function(fun) {\n nms <- unique(c(names(formals(fun)), all.vars(body(fun), functions = FALSE)))\n invalid <- endsWith(nms, \"_\") | startsWith(nms, \"_\") | nms %in% c(\n\n # clashes with Fortran subroutine symbols\n \"c_int\", \"c_double\", \"c_ptrdiff_t\",\n\n # clashes with C bridge symbols\n \"int\" #, \"double\",\n\n # ??? (clashes with R symbols?)\n # \"double\", \"integer\"\n )\n if (any(invalid)) {\n stop(\"symbols cannot start or end with '_', but found: \",\n glue_collapse(invalid, \", \", last = \", and \"))\n }\n}\n\n\n\n# ---- utils ----\n\nmake_unique_name <- local({\n i <- 0L\n function(prefix = \"tmp\") {\n paste0(prefix, i <<- i + 1L)\n }\n})\n"], ["/quickr/R/classes.R", "#' @import S7\nNULL\n\nnew_setter <- function(coerce = NULL, coerce_null = FALSE, set_once = FALSE, env = parent.frame(2L)) {\n\n if (is.null(coerce) || isFALSE(coerce) && isFALSE(set_once))\n return()\n\n bind_name <- quote(name <- as.character(last(attr(self, \".setting_prop\", TRUE))))\n\n check_set_once <- if (set_once) {\n quote(if (!is.null(prop(self, name)))\n stop(name, \" can only be set once\"))\n }\n\n rebind_coerced_value <-\n if (is.null(coerce) || isFALSE(coerce)) {\n NULL\n } else if (isTRUE(coerce)) {\n quote(value <- convert(\n from = value,\n to = S7_class(self)@properties[[as.character(name)]]$class\n ))\n } else if (is.function(coerce) || is.symbol(coerce)) {\n bquote(value <- .(coerce)(value))\n } else if (is.language(coerce)) {\n bquote(value <- .(coerce))\n } else {\n stop(\"coerce must be TRUE, FALSE, NULL, a function, a symbol, or a call\")\n }\n\n if (!coerce_null && !is.null(rebind_coerced_value)) {\n rebind_coerced_value <- bquote(if (!is.null(value)) .(rebind_coerced_value))\n }\n\n set <- quote(`prop<-`(\n object = self,\n name = name,\n check = FALSE,\n value = value\n ))\n\n new_function(\n args = alist(self = , value = ),\n body = as.call(c(quote(`{`),\n bind_name,\n check_set_once,\n rebind_coerced_value,\n set)),\n env = env\n )\n}\n\n\nnew_scalar_validator <- function(allow_null = FALSE,\n allow_na = FALSE,\n additional_checks = NULL,\n env = parent.frame(2L)) {\n checks <- c(\n if (allow_null) quote(if (is.null(value)) return()),\n quote(if (length(value) != 1L) return(\"must be a scalar\")),\n if (!allow_na) quote(if (anyNA(value)) return(\"must not be NA\")),\n additional_checks\n )\n\n new_function(\n args = alist(value = ),\n body = as.call(c(quote(`{`), checks)),\n env = parent.frame(2L)\n )\n}\n\n\nprop_bool <- function(default, allow_null = FALSE, allow_na = FALSE, set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n new_property(\n class = if (allow_null) NULL | class_logical else class_logical,\n setter = new_setter(set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null,\n allow_na = allow_na),\n default = default\n )\n}\n\n\nprop_string <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = FALSE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(as.character)\n\n new_property(\n class = if (allow_null) NULL | class_character else class_character,\n default = default,\n validator = new_scalar_validator(allow_null = allow_null),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once)\n )\n}\n\n\nprop_wholenumber <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = TRUE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(\n if (is_wholenumber(value)) as.integer(value)\n else stop(\"@\", name, \" must be a whole number, but received: \", value)\n )\n\n new_property(\n class = if (allow_null) NULL | class_integer else class_integer,\n default = as.integer(default),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null)\n )\n}\n\n\nprop_enum <- function(values,\n nullable = FALSE,\n default = if (nullable) NULL else values[1],\n exact = FALSE,\n set_once = FALSE) {\n\n stopifnot(\n \"values must be a character vector of length >= 2 without any NA\" =\n is.character(values) && length(values) >= 2 && !anyNA(values)\n )\n\n coerce <- if (exact) NULL else {\n bquote(if (length(value) == 1L && !anyNA(i <- charmatch(value, .(values))))\n .(values)[i] else value)\n }\n\n display_values <- glue_collapse(single_quote(values), sep = \", \", last = \", or \")\n msg <- sprintf(\"must be either %s, not '\", display_values)\n validator <- new_scalar_validator(allow_null = nullable,\n additional_checks = bquote(\n if (!match(value, .(values), nomatch = 0L))\n return(paste0(.(msg), value, \"'.\"))\n ))\n\n new_property(\n class = if (nullable) NULL | class_character else class_character,\n setter = new_setter(coerce = coerce, coerce_null = !nullable, set_once = set_once),\n validator = validator,\n default = default\n )\n}\n\n\n.atomic_type_names <- c(\"integer\", \"logical\", \"double\",\n \"character\", \"raw\", \"complex\")\n\n\n# the print method for this should only print non-null values\nVariable := new_class(\n properties = list(\n\n mode = prop_enum(.atomic_type_names, nullable = TRUE, set_once = FALSE),\n\n dims = new_property(\n # NULL means scalar\n NULL | class_list,\n setter = function(self, value) {\n if (!length(value))\n return(self)\n\n value <- switch(typeof(value),\n logical = , integer = , double = as.list(value),\n language = , symbol = list(value), # implicit rank-1\n list = value,\n stop(\"@dims must be a list\")\n )\n\n value <- lapply(value, \\(axis) {\n if (is.language(axis)) {\n axis\n } else if (is_wholenumber(axis) || is_scalar_na(axis)) {\n as.integer(axis)\n } else {\n stop(sprintf(\n \"%s@dims must be a list of language or scalar integers, not %s\",\n self@name %||% '', axis\n ))\n }\n })\n\n self@dims <- value\n self\n } # dims$setter\n ), # dims = new_property()\n\n name = prop_string(\n allow_null = TRUE,\n coerce = quote(switch(typeof(value), symbol = as.character(value), value)),\n set_once = FALSE #TRUE\n ),\n\n rank = new_property(\n class_integer,\n getter = function(self) {\n length(self@dims)\n }),\n\n modified = prop_bool(default = FALSE),\n\n r = new_property(\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n # custom setter to workaround https://github.com/RConsortium/S7/issues/511\n attr(self, \"r\") <- value\n self\n }\n ),\n\n is_arg = prop_bool(default = FALSE),\n\n is_return = prop_bool(default = FALSE),\n\n # TRUE for closure args and return values, FALSE for all other vars.\n is_external = new_property(\n class_logical,\n getter = function(self)\n self@is_arg || self@is_return\n ),\n\n is_scalar = new_property(\n class_logical,\n getter = function(self) {\n self@rank == 0 || identical(self@dims, list(1L))\n }\n )\n\n )\n)\n\n# method(print, Variable) <- function(x, ...) {\n#\n# }\n\n\n\nFortran := new_class(\n class_character,\n\n properties = list(\n\n value = NULL | Variable,\n\n r = new_property(\n # custom setter only to workaround https://github.com/RConsortium/S7/issues/511\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n attr(self, \"r\") <- value\n self\n }\n )\n ),\n\n validator = function(self) {\n if (length(self) != 1L)\n \"must be a length 1 string\"\n }\n)\n\n\nFortranSubroutine := new_class(Fortran, properties = list(\n name = prop_string(),\n signature = class_character,\n closure = class_function,\n scope = NULL | class_environment,\n c_bridge = S7::new_property(\n NULL | class_character,\n getter = function(self) {\n make_c_bridge(self) %error% NULL\n })\n))\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\ntry_prop <- function(object, name) S7::prop(object, name) %error% NULL\n\nemit <- function(..., sep = \"\", end = \"\\n\") cat(..., end, sep = sep)\n\nmethod(format, Variable) <- function(x, ...) {\n capture.output(str(x))\n}\n\nmethod(as.character, Variable) <- function(x, ...)\n x@name %||% stop(\"Variable does not have a name\")\n\nmethod(print, Fortran) <- function(x, ...) {\n emit(trimws(x), end = \"\\n\\n\")\n for(prop_name in c(\"value\", \"r\", \"c_bridge\"))\n if (!is.null(prop_val <- try_prop(x, prop_name))) {\n emit(\"@\", prop_name, \": \", trimws(indent(format(prop_val))));\n }\n}\n"], ["/quickr/R/aaa-utils.R", "#' @importFrom glue glue glue_data trim as_glue glue_collapse single_quote\n#' @importFrom dotty .\n#' @importFrom stats setNames\n#' @importFrom utils gethash hashtab remhash sethash str\nNULL\n\n# @export\n# This will be exported by S7 next release.\n`:=` <- function(left, right) {\n name <- substitute(left)\n if (!is.symbol(name))\n stop(\"left hand side must be a symbol\")\n\n right <- substitute(right)\n if (!is.call(right))\n stop(\"right hand side must be a call\")\n\n if (is.symbol(cl <- right[[1L]]) &&\n as.character(cl) %in% c(\"function\", \"new.env\")) {\n # attach \"name\" attr for usage like:\n # foo := function(){}\n # foo := new.env()\n right <- eval(right, parent.frame())\n attr(right, \"name\") <- as.character(name)\n } else {\n # for all other usage,\n # inject name as a named arg, so that\n # foo := new_class(...)\n # becomes\n # foo <- new_class(..., name = \"foo\")\n\n right <- as.call(c(as.list(right), list(name = as.character(name))))\n\n ## skip check; if duplicate 'name' arg is an issue the call itself will signal an error.\n # if (hasName(right, \"name\")) stop(\"duplicate `name` argument.\")\n\n ## alternative code path that injects `name` as positional arg instead\n # right <- as.list(right)\n # right <- as.call(c(right[[1L]], as.character(name), right[-1L]))\n }\n\n eval(call(\"<-\", name, right), parent.frame())\n}\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\n`append<-` <- function(x, after, value) {\n if (missing(after))\n c(x, value)\n else\n append(x, value, after = after)\n}\n\n`append1<-` <- function (x, value) {\n stopifnot(is.list(x) || identical(mode(x), mode(value)))\n x[[length(x) + 1L]] <- value\n x\n}\n\n`prepend<-` <- function(x, value) {\n c(vector(typeof(x)), value, x)\n}\n\n`add<-` <- `+` #function(x, value) x + value\n\nmap_int <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = 0L, ...)\nmap_lgl <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)\nmap_chr <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = \"\", ...)\n\nimap <- function (.x, .f, ...) {\n out <- .mapply(.f, list(.x, names(.x) %||% seq_along(.x)),\n list(...))\n names(out) <- names(.x)\n out\n}\n\nmap2 <- function (.x, .y, .f, ...) {\n if (length(.x) != length(.y) && length(.x) != 1L && length(.y) != 1L)\n stop(\".x and .y must have the same length, or one of them must have length 1\")\n out <- .mapply(.f, list(.x, .y), list(...))\n if (length(.x) == length(out))\n names(out) <- names(.x)\n out\n}\n\ndiscard <- function(.x, .f, ...)\n .x[!vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\nkeep <- function(.x, .f, ...)\n .x[vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\ncompact <- function(.x)\n .x[as.logical(lengths(.x, use.names = FALSE))]\n\ndrop_nulls <- function(x, i) {\n if (missing(i))\n x[!vapply( X = x, FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)]\n else {\n drop <- logical(length(x))\n names(drop) <- names(x)\n drop[i] <- vapply(X = x[i], FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)\n x[!drop]\n }\n}\n\nlast <- function(x) x[[length(x)]]\ndrop_last <- function(x) x[-length(x)]\n\nis_scalar_na <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && is.na(x)\nis_scalar_atomic <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_scalar_integer <- function(x) is.integer(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_string <- function(x) is.character(x) && length(x) == 1L && !is.na(x) # could also be 'glue' class.\nis_bool <- function(x) is.logical(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_number <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_wholenumber <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x) &&\n x >= 0L && (is.integer(x) || is.double(x) && trunc(x) == x)\n\nnew_function <- function(args = NULL, body = NULL, env = parent.frame()) {\n as.function.default(c(args, body %||% list(NULL)), env)\n}\n\nis_call <- function(x, name = NULL) {\n is.call(x) && (is.null(name) || identical(as.symbol(name), x[[1L]]))\n}\n\nstr_flatten <- function(x, collapse = \"\") {\n paste0(as.character(unlist(x, use.names = FALSE)), collapse = collapse)\n}\n\nstr_flatten_lines <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \"\\n\")\n}\n\nstr_flatten_commas <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \", \")\n}\n\nstr_flatten_args <- function(..., multiline = length(dots) >= 3) {\n dots <- unlist(c(character(), ...), use.names = FALSE)\n if (multiline) {\n dots <- paste0(\"\\n \", dots, collapse = \",\")\n paste(dots, \"\\n\")\n } else {\n paste0(dots, collapse = \",\")\n }\n}\n\ninterleave <- function(x, y) {\n stopifnot(is.atomic(x), is.atomic(y), length(y) == 1L, typeof(x) == typeof(y))\n drop_last(as.vector(rbind(x, y, deparse.level = 0L)))\n}\n\nstr_split_lines <- function(...) {\n x <- c(...) |>\n unlist(use.names = FALSE) |>\n strsplit(\"\\n\", fixed = TRUE)\n x[!lengths(x)] <- \"\"\n x |>\n unlist(use.names = FALSE) |>\n trimws(\"right\")\n}\n\nindent <- function(x, n = 2L) {\n x <- str_split_lines(x)\n x <- sub(\"[ \\t\\r]+$\", \"\", x, perl = TRUE) # trim trailing whitespace\n paste0(strrep(\" \", n), x, collapse = \"\\n\")\n}\n\nparent.pkg <- function(env = parent.frame(2)) {\n if (isNamespace(env <- topenv(env)))\n as.character(getNamespaceName(env)) # unname\n else\n NULL # print visible\n}\n\nset_names <- function(x, nm = x, ...) {\n names(x) <- as.character(\n if (is.function(nm)) nm(names(x), ...)\n else unlist(list(nm, ...), use.names = FALSE)\n )\n x\n}\n\nzip_lists <- function(...) {\n x <- if (...length() == 1L) ..1 else list(...)\n\n if (is.character(nms.1 <- names(x.1 <- x[[1L]])))\n if (anyDuplicated(nms.1) || anyNA(nms.1) || any(nms.1 == \"\"))\n stop(\"All names must be unique.\",\n \" (Use `unname()` for positional matching.)\")\n\n if (length(setdiff(lengths(x), 1L)) != 1L)\n stop(\"all elements must have the same length\")\n\n for (i in seq_along(x)) {\n if (identical(nms.1, nms.i <- names(x[[i]])))\n next\n if (setequal(nms.1, nms.i)) {\n x[[i]] <- x[[i]][nms.1]\n next\n }\n stop(\"All names of arguments provided to `zip_lists()` must match.\",\n \" Call `unname()` on each argument if you want positional matching\")\n }\n ans <- .mapply(list, x, NULL)\n names(ans) <- nms.1\n ans\n}\n\nis_missing <- function(x) missing(x) || identical(x, quote(expr = ))\n\nis_type_call <- function(e) {\n is.call(e) && identical(e[[1]], quote(type))\n}\n\nreduce <- function (.x, .f, ..., .init) {\n f <- function(x, y) .f(x, y, ...)\n Reduce(f, .x, init = .init)\n}\n\nsubstitute_ <- function(expr, env) {\n do.call(base::substitute, list(expr, env))\n}\n\ndefer <- function (expr, env = parent.frame(), after = FALSE) {\n thunk <- as.call(list(function() expr))\n do.call(on.exit, list(thunk, TRUE, after), envir = env)\n}\n\nis_scalar <- function(x) identical(length(x), 1L)\n"], ["/quickr/R/scope.R", "\n\nnew_ordered_env <- function(parent = emptyenv()) {\n env <- new.env(parent = parent)\n class(env) <- \"quickr_ordered_env\"\n env\n}\n\n#' @export\n`[[<-.quickr_ordered_env` <- function(x, name, value) {\n attr(x, \"ordered_names\") <- unique(c(attr(x, \"ordered_names\", TRUE), name))\n assign(name, value, envir = x)\n x\n # NextMethod()\n}\n\n#' @export\n`[[.quickr_ordered_env` <- function(x, name) {\n get0(name, x) # name can be a symbols too\n}\n\n#' @export\nnames.quickr_ordered_env <- function(x) {\n all_names <- ls(envir = x, sorted = FALSE)\n ordered_names <- attr(x, \"ordered_names\", TRUE)\n if (!setequal(all_names, ordered_names)) {\n warning(\"untracked name\")\n stop(\"untracked name\")\n }\n ordered_names\n}\n\n#' @export\nas.list.quickr_ordered_env <- function(x, ...) {\n out <- as.list.environment(x, all.names = TRUE, ...)\n out[names.quickr_ordered_env(x)]\n}\n\n#' @export\nprint.quickr_ordered_env <- function(x, ...) {\n emit(\"env (class: \", str_flatten_commas(class(x)), \") with bindings:\")\n str(as.list.quickr_ordered_env(x), no.list = TRUE)\n}\n\n\ncheck_assignment_compatible <- function(target, value) {\n if (is.null(value)) return()\n stopifnot(exprs = {\n inherits(target, Variable)\n inherits(value, Variable)\n passes_as_scalar(target) || passes_as_scalar(value) || target@rank == value@rank\n })\n}\n\nnew_scope <- function(closure, parent = emptyenv()) {\n scope <- new_ordered_env(parent = parent)\n class(scope) <- unique(c(\"quickr_scope\", class(scope)))\n attr(scope, \"closure\") <- closure\n\n\n attr(scope, \"get_unique_var\") <- local({\n i <- 0L\n function(...) {\n name <- paste0(\"tmp\", i <<- i + 1L, \"_\")\n (scope[[name]] <- Variable(..., name = name))\n }\n })\n attr(scope, \"assign\") <- function(name, value) {\n stopifnot(inherits(value, Variable), is.symbol(name) || is_string(name))\n name <- as.character(name)\n if (exists(name, scope))\n check_assignment_compatible(get(name, scope), value)\n value@name <- name\n assign(name, value, scope)\n }\n scope\n}\n\n\n#' @export\n`@.quickr_scope` <- function(x, name) attr(x, name, exact = TRUE)\n\n#' @export\n`@<-.quickr_scope` <- function(x, name, value) `attr<-`(x, name, value = value)\n\n#' @importFrom utils .AtNames findMatches\n#' @export\n.AtNames.quickr_scope <- function(x, pattern = \"\")\n findMatches(pattern, names(attributes(x)))\n\n"], ["/quickr/R/preprocess-lang.R", "\n\ndefuse_numeric_literals <- function(e) {\n if (is.call(e)) {\n e <- as.call(lapply(e, defuse_numeric_literals))\n if (is.symbol(e1 <- e[[1L]]) &&\n as.character(e1) %in% c(\"+\", \"-\", \"*\", \"/\", \"%%\", \"%/%\", \"^\") &&\n all(map_lgl(e[-1L], is.atomic))) {\n e <- eval(e, baseenv())\n }\n }\n e\n}\n\n\nensure_last_expr_sym <- function(bdy) {\n if (!is_call(bdy, quote(`{`)))\n stop(\"bad body, needs {\")\n if (!is.symbol(last_expr <- last(bdy))) {\n bdy[[length(bdy)]] <- call(\"<-\", quote(out_), last_expr)\n bdy[[length(bdy) + 1L]] <- quote(out_)\n }\n bdy\n}\n\n\nwhole_doubles_to_ints <- function(x) {\n walker <- function(x) {\n switch(\n typeof(x),\n double = if (trunc(x) == x) as.integer(x),\n language = as.call(lapply(x, walker)),\n list = lapply(x, walker),\n x\n )\n }\n walker(x)\n}\n"], ["/quickr/R/zzz.R", "# # ' @export\n# `@.default` <- function(x, name) {\n# if (isS4(x))\n# methods::slot(x, name)\n# else\n# attr(x, name, TRUE)\n# }\n#\n# # ' @export\n# `@<-.default` <- function(x, name, value) {\n# if (isS4(x))\n# methods::`slot<-`(x, name, value = value)\n# else\n# `attr<-`(x, name, value)\n# }\n#\n# # ' @importFrom utils .AtNames findMatches\n# .AtNames.default <- function(x, pattern = \"\") {\n# if (isS4(x))\n# findMatches(pattern, methods::slotNames(x))\n# else\n# findMatches(pattern, names(attributes(x)))\n# }\n#\n# on_load_register_.AtNames.default <- function() {\n# # if we register via NAMESPACE, we get warning\n# # about overwriting utils:::.AtNmaes.default\n# registerS3method(\".AtNames\", \"default\", .AtNames.default)\n# }\n\n.onLoad <- function(...) {\n S7::methods_register()\n asNamespace(\"dotty\")$dotify()\n # on_load_register_.AtNames.default()\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-21 01:15:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(fsub, strict = TRUE, headers = TRUE) {}", "code_description": "This code segment functions to: Generate interface code facilitating interoperability between different programming environments by handling memory allocation, type validation, and data structure conversion while ensuring argument consistency and managing resource protection."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(fsub, strict = TRUE, headers = TRUE) {\n closure <- fsub@closure\n scope <- environment(closure)\n return_var_name <- closure_return_var_name(closure)\n return_var <- get(return_var_name, scope)\n\n c_code <- character()\n\n if (headers) {\n append(c_code) <- c(\n '#include <R.h>',\n '#include <Rinternals.h>',\n '')\n }\n\n append(c_code) <- fsub_extern_decl(fsub)\n\n # Process closure arguments\n arg_vars <- mget(fsub@signature[!sapply(fsub@signature, is_size_name)], scope)\n arg_code <- map(arg_vars, closure_arg_c_defs, strict = strict)\n append(c_code) <- unlist(arg_code)\n\n # Add size checks\n size_checks <- map(arg_vars, closure_arg_size_checks, scope = scope)\n append(c_code) <- unlist(size_checks)\n\n # Prepare return variable\n append(c_code) <- return_var_c_defs(return_var, scope)\n\n # Generate fsub call\n fsub_args <- map_chr(fsub@signature, function(name) {\n if (is_size_name(name)) name else paste0(get(name, scope)@name, \"__\")\n })\n append(c_code) <- glue(\"{fsub@name}({str_flatten_commas(fsub_args)});\")\n\n # Finalize return value\n append(c_code) <- c(\n 'UNPROTECT(1);',\n glue('return {return_var@name};'))\n\n # Add error handling for argument count\n c_code <- c(\n 'if (CDR(Rf_length(args)) != Rf_length(CDR(args)))',\n ' Rf_error(\"... must contain exactly %i arguments\", Rf_length(args));',\n '',\n c_code)\n\n as_glue(str_flatten_lines(c_code))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-16-20"}, "editdistance_info": {"edit_distance": 24.6847, "calculate_time": "2025-08-21 01:16:20", "true_code_clean": "function(fsub, strict = TRUE, headers = TRUE) {\n stopifnot(inherits(fsub, FortranSubroutine))\n closure <- fsub@closure\n scope <- fsub@scope\n fsub_arg_names <- fsub@signature \n closure_arg_names <- names(formals(closure))\n c_body <- character()\n if (!all(closure_arg_names %in% fsub_arg_names))\n stop(\"Undeclared arguments: \", str_flatten_commas(setdiff(closure_arg_names, fsub_arg_names)))\n closure_arg_vars <- mget(closure_arg_names, scope)\n append(c_body) <- lapply(closure_arg_vars, closure_arg_c_defs, strict = strict) |>\n rbind(\"\")\n append(c_body) <- lapply(closure_arg_vars, closure_arg_size_checks, scope = scope)\n n_protected <- 0L\n return_var <- get(closure_return_var_name(closure), scope)\n if (!return_var@name %in% closure_arg_names) {\n return_var@modified <- TRUE\n assign(return_var@name, return_var, scope)\n append(c_body) <- return_var_c_defs(return_var, fsub@scope)\n add(n_protected) <- 1L \n if (return_var@rank > 1)\n add(n_protected) <- 1L \n }\n fsub_call_args <- fsub_arg_names |>\n lapply(\\(nm) paste0(nm, if (!is_size_name(nm)) \"__\")) |>\n unlist()\n if (length(fsub_call_args) > 3)\n fsub_call_args <- paste0(\"\\n \", fsub_call_args)\n append(c_body) <- c(\"\", glue(\"{fsub@name}({str_flatten_commas(fsub_call_args)});\"), \"\")\n if (n_protected > 0)\n append(c_body) <- glue(\"UNPROTECT({n_protected});\")\n append(c_body) <- glue(\"return {return_var@name};\")\n c_args <- paste(\"SEXP\", names(formals(closure)), collapse = \", \")\n c_body <- as_glue(str_flatten_lines(c_body))\n c_func_def <- glue(\"SEXP {fsub@name}_(SEXP _args) {c_block(c_body)}\")\n fsub_extern_decl <- fsub_extern_decl(fsub)\n c_headers <- glue::trim(r\"--(\n )--\")\n as_glue(str_flatten_lines(c(\n if (headers) c_headers,\n fsub_extern_decl, \"\",\n c_func_def)\n ))\n}", "predict_code_clean": "function(fsub, strict = TRUE, headers = TRUE) {\n closure <- fsub@closure\n scope <- environment(closure)\n return_var_name <- closure_return_var_name(closure)\n return_var <- get(return_var_name, scope)\n c_code <- character()\n if (headers) {\n append(c_code) <- c(\n '\n '\n '')\n }\n append(c_code) <- fsub_extern_decl(fsub)\n arg_vars <- mget(fsub@signature[!sapply(fsub@signature, is_size_name)], scope)\n arg_code <- map(arg_vars, closure_arg_c_defs, strict = strict)\n append(c_code) <- unlist(arg_code)\n size_checks <- map(arg_vars, closure_arg_size_checks, scope = scope)\n append(c_code) <- unlist(size_checks)\n append(c_code) <- return_var_c_defs(return_var, scope)\n fsub_args <- map_chr(fsub@signature, function(name) {\n if (is_size_name(name)) name else paste0(get(name, scope)@name, \"__\")\n })\n append(c_code) <- glue(\"{fsub@name}({str_flatten_commas(fsub_args)});\")\n append(c_code) <- c(\n 'UNPROTECT(1);',\n glue('return {return_var@name};'))\n c_code <- c(\n 'if (CDR(Rf_length(args)) != Rf_length(CDR(args)))',\n ' Rf_error(\"... must contain exactly %i arguments\", Rf_length(args));',\n '',\n c_code)\n as_glue(str_flatten_lines(c_code))\n}"}}
{"repo_name": "quickr", "file_name": "/quickr/R/r2f.R", "inference_info": {"prefix_code": "\n\n\n# Take parsed R code (anything returnable by base::str2lang()) and returns\n# a Fortran object, which is a string of Fortran code and some attributes\n# describing the value.\nlang2fortran <- r2f <- function(e, scope = NULL, ..., calls = character(), hoist = NULL) {\n ## 'hoist()' is a function that individual handlers can call to pre-emit some\n ## Fortran code. E.g., to setup a temporary variable if the generated Fortran\n ## code doesn't neatly translate into a single expression.\n hoisted <- character()\n if (is.null(hoist)) {\n delayedAssign(\"hoist_connection\", textConnection(\"hoisted\", \"w\", TRUE))\n hoist <- function(...) {\n writeLines(as.character(unlist(c(character(), ...))),\n hoist_connection)\n }\n # if performance with textConnection() becomes an issue, maybe switch to an\n # anonymous file(), though, each hoisting context is typically shortlived and\n # usually 0 lines are hoisted per context, and if they are hoisted, a small number.\n }\n\n fortran <- switch(typeof(e),\n language = {\n # a call\n handler <- get_r2f_handler(callable <- e[[1L]])\n\n match.fun <- attr(handler, \"match.fun\", TRUE)\n if (is.null(match.fun)) {\n match.fun <- get0(callable, parent.env(globalenv()),\n mode = \"function\")\n # this is a best effort to, eg. resolve `seq.default` from `seq`.\n # This should likely be moved into attaching the `match.fun` attr\n # to handlers, for more involved resolution (e.g., with getS3Method())\n if (\"UseMethod\" %in% all.names(body(match.fun)))\n match.fun <- get0(paste0(callable, \".default\"),\n parent.env(globalenv()),\n mode = \"function\",\n ifnotfound = match.fun)\n }\n if (typeof(match.fun) == \"closure\") {\n e <- match.call(match.fun, e)\n }\n\n if (isTRUE(getOption(\"quickr.r2f.debug\"))) {\n\n try(handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)) -> res\n if (inherits(res, \"try-error\")) {\n debugonce(handler)\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n }\n\n res\n\n } else {\n\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n\n }\n\n },\n\n integer = ,\n double = ,\n complex = ,\n logical = atomic2Fortran(e),\n\n symbol = {\n s <- as.character(e)\n # logicals that come in from R are passed as integer types,\n # so for all fortran ops we cast to logical with /=0\n if (\n !is.null(scope[[e]] -> val) &&\n val@mode == \"logical\" &&\n val@is_external\n ) {\n s <- paste0(\"(\", s, \"/=0)\")\n }\n Fortran(s, value = scope[[e]])\n },\n\n ## handling 'object' and 'closure' here are both bad ideas,\n ## TODO: delete both\n # \"object\" = {\n # if (inherits(e, Variable))\n # e <- Fortran(character(), e)\n # stopifnot(inherits(e, Fortran))\n # e\n # },\n\n closure = {\n if (is.null(name <- attr(e, \"name\", TRUE))) {\n name <- if (is.symbol(name <- substitute(e)))\n as.character(name)\n else\n \"anonymous_function\"\n }\n\n stopifnot(is.null(scope))\n new_fortran_subroutine(name, e)\n },\n\n ## all the other typeof() possible values\n # \"character\",\n # \"raw\" ,\n # \"list\",\n # \"NULL\",\n # \"function\",\n # \"special\",\n # \"builtin\",\n # \"environment\",\n # \"S4\",\n # \"pairlist\",\n # \"promise\",\n # \"char\",\n # \"...\",\n # \"any\",\n # \"expression\",\n # \"externalptr\",\n # \"bytecode\",\n # \"weakref\"\n # default\n stop(\"Unsupported object type encountered: \", typeof(e))\n )\n\n if (length(hoisted)) {\n combined <- str_flatten_lines(c(hoisted, fortran))\n attributes(combined) <- attributes(fortran)\n fortran <- combined\n }\n\n attr(fortran, \"r\") <- e\n fortran\n}\n\n\natomic2Fortran <- function(x) {\n stopifnot(is_scalar_atomic(x))\n s <- switch(typeof(x),\n double =,\n integer = num2fortran(x),\n logical = if (x) \".true.\" else \".false.\",\n complex = sprintf(\"(%s, %s)\", num2fortran(Re(x)), num2fortran(Im(x))))\n Fortran(s, Variable(typeof(x)))\n}\n\nnum2fortran <- function(x) {\n stopifnot(typeof(x) %in% c(\"integer\", \"double\"))\n digits <- 7L\n nsmall <- switch(typeof(x), integer = 0L, double = 1L)\n repeat {\n s <- format.default(x, digits = digits, nsmall = nsmall, scientific = 1L)\n if (x == eval(str2lang(s))) # eval() needed for negative and complex numbers\n break\n add(digits) <- 1L\n if (digits > 22L)\n stop(\"number formatting error: \", x, \" formatted as : \", s)\n }\n paste0(s, switch(typeof(x), double = \"_c_double\", integer = \"_c_int\"))\n}\n\n\nr2f_handlers := new.env(parent = emptyenv())\n\nget_r2f_handler <- function(name) {\n stopifnot(\"All functions called must be named as symbols\" = is.symbol(name))\n get0(name, r2f_handlers) %||% stop(\"Unsupported function: \", name, call. = FALSE)\n}\n\nr2f_default_handler <- function(args, scope = NULL, ..., calls) {\n # stopifnot(is.call(e), is.symbol(e[[1L]]))\n\n x <- lapply(args, r2f, scope = scope, calls = calls, ...)\n s <- sprintf(\"%s(%s)\", last(calls), str_flatten_commas(x[-1]))\n Fortran(s)\n}\n\n## ??? export as S7::convert() methods?\nregister_r2f_handler <- function(name, fun) {\n stopifnot(\n is_string(name),\n identical(formals(fun), alist(x = , scope = NULL))\n )\n\n r2f_handlers[[name]] <- fun\n}\n\n.r2f_handler_not_implemented_yet <- function(e, scope, ...) {\n stop(gettextf(\"'%s' is not implemented yet\", as.character(e[[1L]])),\n call. = FALSE)\n}\n\nr2f_handlers[[\"declare\"]] <- function(args, scope, ...) {\n\n for (a in args) {\n if (is_missing(a)) {\n next\n }\n if (is_type_call(a)) {\n var <- type_call_to_var(a)\n var@is_arg <- var@name %in% names(formals(scope@closure))\n scope[[var@name]] <- var\n } else if (is_call(a, quote(`{`))) {\n Recall(as.list(a)[-1], scope)\n }\n }\n\n Fortran(\"\")\n}\n\n\nr2f_handlers[[\"Fortran\"]] <- function(args, scope = NULL, ...) {\n if (!is_string(args[[1]]))\n stop(\"Fortran() must be called with a string\")\n Fortran(args[[1]])\n # enable passing through literal fortran code\n # used like:\n # Fortran(\"nearest(x, 1)\", double(length(x)))\n # Fortran(\"nearest(x, 1)\", x)\n # Fortran(\"x = nearest(x, 1)\")\n}\n\nr2f_handlers[[\"(\"]] <- function(args, scope, ...) {\n r2f(args[[1L]], scope, ...)\n}\n\nr2f_handlers[[\"{\"]] <- function(args, scope, ..., hoist = NULL) {\n # every top level R-expr / fortran statement gets its own hoist target.\n x <- lapply(args, r2f, scope, ...)\n code <- str_flatten_lines(x)\n\n # browser()\n value <- (if (length(args)) last(x)@value) %||% Variable()\n Fortran(code, value)\n}\n\n\n\n# ---- reduction intrinsics ----\n\n\ncreate_mask_hoist <- function() {\n .hoisted_mask <- NULL\n\n try_set <- function(mask) {\n stopifnot(inherits(mask, Fortran), mask@value@mode == \"logical\")\n # each hoist can only accept one mask.\n if (is.null(.hoisted_mask)) {\n .hoisted_mask <<- mask\n return(TRUE)\n }\n # if the mask is identical, we accept it.\n if (identical(.hoisted_mask, mask)) {\n return(TRUE)\n }\n # can't hoist this mask.\n FALSE\n }\n\n get_hoisted <- function() .hoisted_mask\n\n environment()\n}\n\n\nr2f_handlers[[\"max\"]] <-\nr2f_handlers[[\"min\"]] <-\nr2f_handlers[[\"sum\"]] <-\nr2f_handlers[[\"prod\"]] <- function(args, scope, ...) {\n intrinsic <- switch(last(list(...)$calls),\n max = \"maxval\",\n min = \"minval\",\n sum = \"sum\",\n prod = \"product\")\n\n reduce_arg <- function(arg) {\n mask_hoist <- create_mask_hoist()\n x <- r2f(arg, scope, ..., hoist_mask = mask_hoist$try_set)\n if(x@value@rank == 0)\n return(x)\n hoisted_mask <- mask_hoist$get_hoisted()\n s <- glue(\n if (is.null(hoisted_mask))\n \"{intrinsic}({x})\"\n else\n \"{intrinsic}({x}, mask = {hoisted_mask})\"\n )\n Fortran(s, Variable(x@value@mode))\n }\n\n if (length(args) == 1) {\n reduce_arg(args[[1]])\n } else {\n args <- lapply(args, reduce_arg)\n mode <- reduce_promoted_mode(args)\n s <- switch(last(list(...)$calls),\n max = glue(\"max({str_flatten_commas(args)})\"),\n min = glue(\"min({str_flatten_commas(args)})\"),\n sum = glue(\"({str_flatten(args, ' + ')})\"),\n prod = glue(\"({str_flatten(args, ' * ')})\")\n )\n Fortran(s, Variable(mode))\n }\n}\n\n\nr2f_handlers[[\"which.max\"]] <-\nr2f_handlers[[\"which.min\"]] <-\nfunction(args, scope = NULL, ...) {\n stopifnot(length(args) == 1)\n x <- r2f(args[[1L]], scope, ...)\n stopifnot(\"Values passed to which.max()/which.min() must be 1d arrays\" = x@value@rank == 1)\n valout <- Variable(mode = \"integer\") # integer scalar\n\n if (x@value@mode == \"logical\") {\n val <- switch(last(list(...)$calls),\n which.max = \".true.\",\n which.min = \".false.\")\n f <- glue(\"findloc({x}, {val}, 1)\")\n } else {\n intrinsic <- switch(last(list(...)$calls),\n which.max = \"maxloc\",\n which.min = \"minloc\")\n f <- glue(\"{intrinsic}({x}, 1)\")\n }\n\n Fortran(f, valout)\n}\n\n\nr2f_handlers[[\"[\"]] <- ", "suffix_code": "\n\n\nr2f_handlers[[\":\"]] <- function(args, scope, ...) {\n # depending on context, this translation can vary.\n\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n args <- whole_doubles_to_ints(args)\n .[start, end] <- lapply(args, r2f, scope, ...)\n step <- glue(\"sign(1, {end}-{start})\")\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{start}:{end}:{step}\"),\n \"for\" = glue(\"{start}, {end}, {step}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {start}, {end}, {step}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\nr2f_handlers[[\"seq\"]] <- function(args, scope, ...) {\n args <- whole_doubles_to_ints(args) # only casts if trunc(dbl) == dbl\n if (!is.null(args$length.out) || !is.null(args$along.with)) {\n stop(\"seq(length.out=, along.with=) not implemented yet\")\n }\n\n\n .[from, to, by] <- lapply(args, r2f, scope, ...)[c(\"from\", \"to\", \"by\")]\n by <- by %||% Fortran(glue(\"sign(1, {to}-{from})\"), Variable(\"integer\"))\n\n # Fortran only supports integer sequences in do and implicit do contexts.\n # to make a double sequence, needs to be in via an implied map() call, like\n # seq(1, 10, .1) -> [(x * 0.1, x = 10, 50)]\n #\n # e.g., i <- scope@get_unique_var(\"integer\")\n # glue(\"[({i} * by, {i} = int(from/by), int(to/by))]\")\n if (from@value@mode != \"integer\" ||\n to@value@mode != \"integer\" ||\n by@value@mode != \"integer\")\n stop(\"non-integer seq()'s not implemented yet.\")\n\n # depending on context, this translation can vary.\n #\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{from}:{to}:{by}\"),\n \"for\" = glue(\"{from}, {to}, {by}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {from}, {to}, {by}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\n\n\nr2f_handlers[[\"ifelse\"]] <- function(args, scope, ...) {\n .[mask, tsource, fsource] <- lapply(args, r2f, scope, ...)\n # (tsource, fsource, mask)\n mode <- tsource@value@mode\n dims <- conform(mask@value, tsource@value, fsource@value)@dims\n Fortran(glue(\"merge({tsource}, {fsource}, {mask})\"),\n Variable(mode, dims))\n}\n\n\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- pure elemental unary math intrinsics ----\n\n## real and complex intrinsics\nr2f_handlers[[\"sin\"]] <-\nr2f_handlers[[\"cos\"]] <-\nr2f_handlers[[\"tan\"]] <-\nr2f_handlers[[\"asin\"]] <-\nr2f_handlers[[\"acos\"]] <-\nr2f_handlers[[\"atan\"]] <-\nr2f_handlers[[\"sqrt\"]] <-\nr2f_handlers[[\"exp\"]] <-\nr2f_handlers[[\"log\"]] <-\nr2f_handlers[[\"floor\"]] <-\nr2f_handlers[[\"ceiling\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n intrinsic <- last(list(...)$calls)\n Fortran(glue(\"{intrinsic}({arg})\"), arg@value)\n}\n\nr2f_handlers[[\"log10\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n f <- if(arg@value@mode == \"complex\") {\n glue(\"(log({arg}) / log(10.0_c_double))\")\n } else {\n glue(\"log10({arg})\")\n }\n Fortran(f, arg@value)\n}\n\n## accepts real, integer, or complex\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n if(arg@value@mode == \"complex\")\n arg@value@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- complex elemental unary intrinsics ----\n\nr2f_handlers[[\"Re\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"real({arg})\"), val)\n}\n\nr2f_handlers[[\"Im\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"aimag({arg})\"), val)\n}\n\n# Modulus (magnitude)\nr2f_handlers[[\"Mod\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), val)\n}\n\n# Argument (phase angle, radians)\nr2f_handlers[[\"Arg\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"atan2(aimag({arg}), real({arg}))\"), val)\n}\n\n# conjg() returns a complex value; R uses Conj()\nr2f_handlers[[\"Conj\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"complex\"\n Fortran(glue(\"conjg({arg})\"), val)\n}\n\n\n\n# ---- elemental binary infix operators ----\n\nr2f_handlers[[\"+\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} + {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"-\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} - {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"*\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} * {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"/\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} / {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"^\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} ** {right})\"), conform(left@value, right@value))\n}\n\n\nr2f_handlers[[\">=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} >= {right})\"), var)\n}\nr2f_handlers[[\">\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} > {right})\"), var)\n}\nr2f_handlers[[\"<\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} < {right})\"), var)\n}\nr2f_handlers[[\"<=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} <= {right})\"), var)\n}\nr2f_handlers[[\"==\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} == {right})\"), var)\n}\nr2f_handlers[[\"!=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} /= {right})\"), var)\n}\n\n\n\n# ---- remainder (%%) and integer division (%/%) ----\n#\n# R semantics:\n# x %% y == r where r has the sign of y (divisor)\n# x %/% y == q where q = floor(x / y)\n# and x == r + y * q (within rounding error)\n#\n# Fortran intrinsics:\n# - MODULO(a,p) : remainder with sign(p)\n# - FLOOR(x) : greatest integer ≤ x (real)\n# - AINT(x) : truncation toward 0 (real)\n\nr2f_handlers[[\"%%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n # MODULO gives result with sign(right) – matches R %% behaviour\n Fortran(glue(\"modulo({left}, {right})\"), out_val)\n}\n\nr2f_handlers[[\"%/%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n\n expr <- switch(\n out_val@mode,\n integer = glue(\"int(floor(real({left}) / real({right})))\"),\n double = glue(\"floor({left} / {right})\"),\n stop(\"%/% only implemented for numeric types\")\n )\n\n Fortran(expr, out_val)\n}\n\n\n\n# TODO: the scalar || probably need some more type checking.\n# TODO: gfortran supports implicit casting that of logical to integer when\n# assigning a logical to a variable declared integer, converting `.true.` to `1`,\n# but this is not a standard language feature, and Intel's `ifort` uses `-1` for `.true`.\n# We should explicitly use\n# `merge(1_c_int, 0_c_int, <lgl>)` to cast logical to int.\nr2f_handlers[[\"&\"]] <-\nr2f_handlers[[\"&&\"]] <-\nr2f_handlers[[\"|\"]] <-\nr2f_handlers[[\"||\"]] <-\nfunction(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n args <- lapply(args, function(a) {\n if (a@value@mode != \"logical\") {\n stop(\"must be logical\")\n }\n a\n })\n .[left, right] <- args\n\n operator <- switch(last(list(...)$calls),\n `&` = , `&&` = \".and.\",\n `|` = , `||` = \".or.\")\n\n s <- glue(\"{left} {operator} {right}\")\n val <- conform(left@value, right@value)\n val@mode <- \"logical\"\n Fortran(s, val)\n}\n\n\n\n\n# --- constructors ----\n\n\nr2f_handlers[[\"c\"]] <- function(args, scope = NULL, ...) {\n ff <- lapply(args, r2f, scope, ...)\n s <- glue(\"[ {str_flatten_commas(ff)} ]\")\n lens <- lapply(ff[order(map_int(ff, \\(f) f@value@rank))], function(e) {\n rank <- e@value@rank\n if (rank == 0)\n 1L\n else if (rank == 1)\n e@value@dims[[1]]\n else\n stop(\"all args passed to c() must be scalars or 1-d arrays\")\n })\n mode <- reduce_promoted_mode(ff)\n len <- Reduce(\\(l1, l2) {\n if (is_scalar_na(l1) || is_scalar_na(l2)) {\n NA\n } else if (is_wholenumber(l1) && is_wholenumber(l2)) {\n l1 + l2\n } else {\n call(\"+\", l1, l2)\n }\n }, lens)\n Fortran(s, Variable(mode, list(len)))\n}\n\n\nr2f_handlers[[\"cbind\"]] <- function(e, scope) {\n .NotYetImplemented()\n ee <- lapply(e[-1], r2f, scope)\n ncols <- lapply(ee, function(f) {\n if (f@value@rank %in% c(0, 1))\n 1\n else if (f@value@rank == 2)\n f@value@dims[[2]]\n })\n ncols <- Reduce(\\(a, b) call(\"+\", a, b), ncols)\n ncols <- eval(ncols, scope@sizes)\n}\n\n\n\nr2f_handlers[[\"<-\"]] <- function(args, scope, ...) {\n target <- args[[1]]\n if (is.call(target)) {\n # given a call like `foo(x) <- y`, dispatch to `foo<-`\n target_callable <- target[[1]]\n stopifnot(is.symbol(target_callable))\n name <- as.symbol(paste0(as.character(target_callable), \"<-\"))\n handler <- get_r2f_handler(name)\n return(handler(args, scope, ...)) # new hoist target\n }\n\n # It sure seems like it's be nice if the Fortran() constructor\n # took mode and dims as args directly,\n # without needing to go through Variable...\n stopifnot(is.symbol(target))\n name <- as.character(target)\n\n value <- args[[2]]\n value <- r2f(value, scope, ...)\n\n # immutable / copy-on-modify usage of Variable()\n if (is.null(var <- get0(name, scope))) {\n # this is a binding to a new symbol\n var <- value@value\n var@name <- name\n scope[[name]] <- var\n\n } else {\n # The var already exists, this assignment is a modification / reassignment\n check_assignment_compatible(var, value@value)\n var@modified <- TRUE\n # could probably drop this @modified property, and instead track\n # if the var populated by declare is identical at the end (e.g., perhaps by\n # address, or by attaching a unique id to each var, or ???)\n assign(name, var, scope)\n }\n\n Fortran(glue(\"{name} = {value}\"))\n}\n\n\nr2f_handlers[[\"[<-\"]] <- function(args, scope = NULL, ...) {\n\n # TODO: handle logical subsetting here, which must become a where a construct like:\n # x[lgl] <- val\n # becomes\n # where (lgl)\n # x = val\n # end where\n # ! but if {va} references {x}, it will only see the subset x, not the full {x}\n # e.g.,\n # sum(x) is not the same as `where lgl \\n sum(x) \\n end where`\n # ditto for ifelse() ?\n # e <- as.list(e)\n\n stopifnot(is_call(target <- args[[1L]], \"[\"))\n target <- r2f(target, scope)\n\n value <- r2f(args[[2L]], scope)\n Fortran(glue(\"{target} = {value}\"))\n}\n\nreduce_promoted_mode <- function(...) {\n\n getmode <- function(d) {\n if (inherits(d, Fortran))\n d <- d@value\n if (inherits(d, Variable))\n return(d@mode)\n if (is.list(d) && length(d))\n lapply(d, getmode)\n }\n modes <- unique(unlist(getmode(list(...))))\n\n if (\"double\" %in% modes)\n \"double\"\n else if (\"integer\" %in% modes)\n \"integer\"\n else if (\"logical\" %in% modes)\n \"logical\"\n else\n NULL\n\n}\n\n\nr2f_handlers[[\"=\"]] <- r2f_handlers[[\"<-\"]]\n\nr2f_handlers[[\"logical\"]] <- function(args, scope, ...) {\n Fortran(\".false.\", Variable(mode = \"logical\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"integer\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"integer\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"double\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"double\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"numeric\"]] <- r2f_handlers[[\"double\"]]\n\nr2f_handlers[[\"character\"]] <- r2f_handlers[[\"raw\"]] <-\n .r2f_handler_not_implemented_yet\n\n\nr2f_handlers[[\"matrix\"]] <- function(args, scope = NULL, ...) {\n\n args$data %||% stop(\"matrix(data=) must be provided, cannot be NA\")\n out <- r2f(args$data, scope, ...)\n out@value@dims <- r2dims(list(args$nrow, args$ncol), scope)\n out\n\n # TODO: reshape() if !passes_as_scalar(out)\n}\n\n\n\nconform <- function(..., mode = NULL) {\n var <- NULL\n # technically, types are implicit promoted, but we'll let <- handle that.\n for (var in drop_nulls(list(...))) {\n if (passes_as_scalar(var)) {\n next\n } else {\n break\n }\n }\n if (is.null(var))\n NULL\n else\n Variable(mode %||% var@mode, var@dims)\n }\n\n\n\n# ---- printers ----\n\n\nr2f_handlers[[\"cat\"]] <- function(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n # can do a lot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"character\")\n label <- args[[1]]\n if (!endsWith(label, \"\\n\"))\n stop(\"cat(<strings>) must end with '\\n'\")\n label <- substring(label, 1, nchar(label)-1)\n\n Fortran(glue('call labelpr(\"{label}\", {nchar(label)})'))\n}\n\nr2f_handlers[[\"print\"]] <- function(args, scope = NULL, ...) {\n # args <- lapply(as.list(e)[-1], r2f, scope)\n # args <- as.list(e)[-1]\n # can do alot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"symbol\")\n name <- args[[1]]\n var <- get(name, envir = scope)\n name <- as.character(name)\n if (var@mode == \"logical\")\n name <- sprintf(\"(%s/=0)\", name)\n label <- \"\"\n # browser()\n if (passes_as_scalar(var)) {\n # } \"scalar\"\n # paste0(c(var@mode, scalar) collapse = \"_\"),\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr1\",\n double = \"dblepr1\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name})'))\n } else {\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr\",\n double = \"dblepr\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name}, size({name}))'))\n }\n}\n\n# r2f_handlers[[\"ifelse\"]] <- function(e, scope) {\n# # TODO:\n# # <- and [<- need to be aware of this construct for it to make sense.\n# .[test, yes, no] <- lapply(e[-1], r2f, scope)\n# Fortran(glue(\"where ({test}}\n# {indent(yes)}\n# elsewhere\n# {indent({no})\n# end where\"))\n# }\n\n\nr2f_handlers[[\"length\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x})\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"nrow\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 1)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"ncol\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 2)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"dim\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"shape({x})\"), Variable(\"integer\", x@value@rank))\n}\n\n\n\n\n# this is just `[` handler\nr2f_slice <- function(args, scope, ...) { }\n\n\n\n# ---- control flow ----\n\n\nr2f_handlers[[\"if\"]] <- function(args, scope, ..., hoist = NULL) {\n # cond uses the current hoist context.\n cond <- r2f(args[[1]], scope, ..., hoist = hoist)\n\n # true and false branchs gets their own hoist target.\n true <- r2f(args[[2]], scope, ..., hoist = NULL)\n\n if (length(args) == 2) {\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n end if\n \"))\n } else {\n false <- r2f(args[[3]], scope, ..., hoist = NULL)\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n else\n {indent(false)}\n end if\n \"))\n }\n}\n\n\n# TODO: return\n\n# ---- repeat ----\nr2f_handlers[[\"repeat\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n body <- r2f(args[[1]], scope, ...)\n Fortran(glue(\n \"do\n {indent(body)}\n end do\n \"))\n}\n\n# ---- break ----\nr2f_handlers[[\"break\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"exit\")\n}\n\n# ---- break ----\nr2f_handlers[[\"next\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"cycle\")\n}\n\n# ---- while ----\nr2f_handlers[[\"while\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 2L)\n cond <- r2f(args[[1]], scope, ...)\n body <- r2f(args[[2]], scope, ...) ## should we set a new hoist target here?\n Fortran(glue(\n \"do while ({cond})\n {indent(body)}\n end do\n \"))\n}\n\n## ---- for ----\nr2f_iterable <- function(e, scope, ...) {\n .NotYetImplemented()\n\n if (is.symbol(e)) {\n var <- get(e, scope)\n iterable <- r2f(...)\n }\n\n # list(var, iterable, body_prefix)\n}\n\n\n\n\nr2f_handlers[[\"for\"]] <- function(args, scope, ...) {\n .[var, iterable, body] <- args\n stopifnot(is.symbol(var))\n var <- as.character(var)\n scope[[var]] <- Variable(mode = \"integer\", name = var)\n\n iterable <- r2f_iterable_handlers[[as.character(iterable[[1]])]](iterable, scope)\n body <- r2f(body, scope, ...)\n\n Fortran(glue(\n \"do {var} = {iterable}\n {indent(body)}\n end do\n \"))\n}\n\nr2f_iterable_handlers := new.env()\n\nr2f_iterable_handlers[[\"seq_len\"]] <- function(e, scope, ...) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_len()\")\n x <- x[[1]]\n start <- 1L\n end <- r2f(x)\n glue(\"{start}, {end}\")\n}\n\nr2f_iterable_handlers[[\"seq\"]] <- function(e, scope) {\n\n ee <- match.call(seq.default, e)\n ee <- whole_doubles_to_ints(ee)\n\n start <- r2f(ee$from, scope)\n end <- r2f(ee$to, scope)\n step <- if (is.null(ee$by))\n glue(\"sign(1, {end}-{start})\")\n else\n r2f(ee$by, scope)\n\n str_flatten_commas(\n start, end, step\n )\n}\n\nr2f_iterable_handlers[[\":\"]] <- function(e, scope) {\n\n ee <- whole_doubles_to_ints(e)\n .[start, end] <- as.list(ee)[-1] |> lapply(r2f, scope)\n\n glue(\"{start}, {end}, sign(1, {end}-{start})\")\n}\n\n\n\nr2f_iterable_handlers[[\"seq_along\"]] <- function(e, scope) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_along()\")\n x <- x[[1]]\n start <- 1\n end <- sprintf(\"size(%s)\", r2f(x, scope))\n glue(\"{start}, {end}\")\n}\n\n\n# ---- helpers ----\n\ncheck_call <- function(e, nargs) {\n if (length(e) != (nargs+1L))\n stop(\"Too many args to: \", as.character(e[[1L]]))\n}\n", "middle_code": "function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n var <- args[[1]]\n var <- r2f(var, scope, ...)\n idxs <- whole_doubles_to_ints(args[-1])\n idxs <- imap(idxs, function(idx, i) {\n if (is_missing(idx))\n Fortran(\":\", Variable(\"integer\", var@value@dims[[i]]))\n else\n r2f(idx, scope, ...)\n })\n if (length(idxs) == 1 &&\n idxs[[1]]@value@mode == \"logical\" &&\n idxs[[1]]@value@rank == var@value@rank) {\n mask <- idxs[[1]]\n if (hoist_mask(mask))\n return(var)\n return(Fortran(glue(\"pack({var}, {mask})\"), Variable(var@value@mode, dims = NA)))\n }\n if (length(idxs) != var@value@rank)\n stop(\"number of args to x[...] must match the rank of x, received:\",\n deparse1(as.call(c(quote(`[`,args )))))\n drop <- args$drop %||% TRUE\n idxs <- lapply(idxs, function(subscript) {\n switch(\n paste0(subscript@value@mode, subscript@value@rank),\n logical0 = {\n Fortran(\":\", Variable(\"integer\", NA))\n },\n logical1 = {\n i <- scope@get_unique_var(\"integer\")\n f <- glue(\"pack([({i}, {i}=1, size({subscript}))], {subscript})\")\n return(Fortran(f, Variable(\"int\", NA)))\n },\n integer0 = {\n if (drop)\n subscript\n else\n Fortran(glue(\"{subscript}:{subscript}\"), Variable(\"int\", 1))\n },\n integer1 = {\n subscript\n },\n stop(\n \"all args to x[...] must be logical or integer of rank 0 or 1\",\n deparse1(as.call(c(quote(`[`, args ))))\n )\n )\n })\n dims <- drop_nulls(lapply(idxs, \\(idx) idx@value@dims[[1]]))\n outval <- Variable(var@value@mode, dims)\n Fortran(glue(\"{var}({str_flatten_commas(idxs)})\"), outval)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/quickr/R/c-wrapper.R", "\nmake_c_bridge <- function(fsub, strict = TRUE, headers = TRUE) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n closure <- fsub@closure\n scope <- fsub@scope\n\n fsub_arg_names <- fsub@signature # arg names\n closure_arg_names <- names(formals(closure))\n\n c_body <- character()\n\n if (!all(closure_arg_names %in% fsub_arg_names))\n stop(\"Undeclared arguments: \", str_flatten_commas(setdiff(closure_arg_names, fsub_arg_names)))\n\n closure_arg_vars <- mget(closure_arg_names, scope)\n\n # first unpack all the input vars into named C variables (including sizes and pointer)\n append(c_body) <- lapply(closure_arg_vars, closure_arg_c_defs, strict = strict) |>\n rbind(\"\")\n\n ## TODO, might still need to define a length size for vars where rank>1, if in checks.\n\n # now do all size checks.\n append(c_body) <- lapply(closure_arg_vars, closure_arg_size_checks, scope = scope)\n\n # maybe define and allocate the output var\n n_protected <- 0L\n return_var <- get(closure_return_var_name(closure), scope)\n if (!return_var@name %in% closure_arg_names) {\n return_var@modified <- TRUE\n assign(return_var@name, return_var, scope)\n append(c_body) <- return_var_c_defs(return_var, fsub@scope)\n add(n_protected) <- 1L # allocated return var\n if (return_var@rank > 1)\n add(n_protected) <- 1L # allocated _dim_sexp\n }\n\n fsub_call_args <- fsub_arg_names |>\n lapply(\\(nm) paste0(nm, if (!is_size_name(nm)) \"__\")) |>\n unlist()\n\n if (length(fsub_call_args) > 3)\n fsub_call_args <- paste0(\"\\n \", fsub_call_args)\n\n append(c_body) <- c(\"\", glue(\"{fsub@name}({str_flatten_commas(fsub_call_args)});\"), \"\")\n if (n_protected > 0)\n append(c_body) <- glue(\"UNPROTECT({n_protected});\")\n append(c_body) <- glue(\"return {return_var@name};\")\n\n c_args <- paste(\"SEXP\", names(formals(closure)), collapse = \", \")\n c_body <- as_glue(str_flatten_lines(c_body))\n\n c_func_def <- glue(\"SEXP {fsub@name}_(SEXP _args) {c_block(c_body)}\")\n\n fsub_extern_decl <- fsub_extern_decl(fsub)\n\n c_headers <- glue::trim(r\"--(\n #define R_NO_REMAP\n #include <R.h>\n #include <Rinternals.h>\n\n\n )--\")\n\n as_glue(str_flatten_lines(c(\n if (headers) c_headers,\n fsub_extern_decl, \"\",\n c_func_def)\n ))\n}\n\n\nclosure_arg_c_defs <- function(var, strict = TRUE) {\n\n name <- var@name\n mode <- var@mode\n\n c_code <- character()\n\n name <- var@name\n SEXPTYPE <- sexptype(var@mode)\n protect <- glue(\"SETCAR(_args, {var@name});\")\n\n append(c_code) <- glue(\n \"// {name}\n _args = CDR(_args);\n SEXP {var@name} = CAR(_args);\")\n\n # first maybe duplicate or coerce the SEXP if needed.\n append(c_code) <- glue(\"if (TYPEOF({name}) != {SEXPTYPE}) {{\")\n append(c_code) <- indent(if (strict) {\n glue(r\"(\n Rf_error(\"typeof({name}) must be '{mode}', not '%s'\", R_typeToChar({name}));\n )\")\n } else {\n glue(\"{name} = Rf_coerceVector({name}, {SEXPTYPE});\n {protect}\")\n })\n\n\n if (var@modified) {\n dup <- glue('\n {name} = Rf_duplicate({name});\n {protect}\n ')\n\n if (strict) {\n append(c_code) <- c(\"}\", dup)\n } else {\n append(c_code) <- sprintf(\"} else %s\", dup)\n }\n\n } else {\n append(c_code) <- \"}\"\n }\n\n # define the variable that will be passed to the fsub\n append(c_code) <- glue(\n \"{fsub_arg_var_c_type(var)} {name}__ = {sexpdata(var@mode)}({name});\")\n\n\n if (var@rank == 1) {\n size_name <- get_size_name(var)\n append(c_code) <- glue(\"const R_xlen_t {size_name} = Rf_xlength({var@name});\")\n } else if (var@rank > 1) {\n append(c_code) <- glue(\n 'const int* const {var@name}__dim_ = ({{\n SEXP dim_ = Rf_getAttrib({var@name}, R_DimSymbol);\n if (Rf_length(dim_) != {var@rank}) Rf_error(\n \"{var@name} must be a {var@rank}D-array, but length(dim({var@name})) is %i\",\n (int) Rf_length(dim_));\n INTEGER(dim_);}});'\n )\n append(c_code) <- map_chr(seq_len(var@rank), \\(axis) {\n size_name <- get_size_name(var, axis)\n glue(\"const int {size_name} = {var@name}__dim_[{axis-1}];\")\n })\n } else {\n stop(\"bad rank\")\n }\n\n as_glue(str_flatten_lines(c_code))\n}\n\n\n\nclosure_arg_size_checks <- function(var, scope) {\n imap(var@dims, function(d, axis) {\n # axis is either:\n # - an integer\n # - a symbol of a size_name\n # - a call, consisting of only size_name symbols and basic arithmetic ops.\n size_name <- get_size_name(var, axis)\n\n if (is_scalar_integer(d)) {\n return(glue('\n if ({size_name} != {d})\n Rf_error(\"{friendly_size(var, axis)} must be {d}, not %0.f\",\n (double){size_name});'\n ))\n }\n\n if (is.symbol(d)) {\n if (as.character(d) == size_name) {\n # self-named size_name is expected to be passed along to subroutine\n return()\n } else {\n # it's a constraint for another size\n return(glue('\n if ({d} != {size_name})\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_name(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double){d});'\n ))\n }\n }\n\n if (is.call(d)) {\n size.c <- dims2c(list(d), scope)\n return(glue('{{\n const R_xlen_t expected = {size.c};\n if ({size_name} != expected)\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_expression(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double)expected);\n }}'\n ))\n }\n\n stop(\"bad dim\")\n })\n}\n\n\n\n\nreturn_var_c_defs <- function(var, scope) {\n # allocate the return var.\n name <- var@name\n c_dims <- dims2c(var@dims, scope)\n c_len <- c_dims2c_len(c_dims)\n len_name <- get_size_name(var)\n\n c_code <- c(\n glue(\"const R_xlen_t {len_name} = {c_len};\"),\n glue(switch(\n var@mode,\n double = \"\n SEXP {name} = PROTECT(Rf_allocVector(REALSXP, {len_name}));\n double* {name}__ = REAL({name});\",\n integer = \"\n SEXP {name} = PROTECT(Rf_allocVector(INTSXP, {len_name}));\n int* {name}__ = INTEGER({name});\",\n complex = \"\n SEXP {name} = PROTECT(Rf_allocVector(CPLXSXP, {len_name}));\n Rcomplex* {name}__ = COMPLEX({name});\",\n logical = \"\n SEXP {name} = PROTECT(Rf_allocVector(LGLSXP, {len_name}));\n int* {name}__ = LOGICAL({name});\"\n )))\n\n if (var@rank > 1) {\n append(c_code) <- c_block(\n glue(\"\n const SEXP _dim_sexp = PROTECT(Rf_allocVector(INTSXP, {var@rank}));\n int* const _dim = INTEGER(_dim_sexp);\"\n ),\n imap(c_dims, function(d, i) {\n glue(\"_dim[{i-1}] = {d};\")\n }),\n glue(\"Rf_dimgets({var@name}, _dim_sexp);\")\n )\n }\n\n str_flatten_lines(c_code)\n}\n\n\n\n\ndims2c_eval_base_env <- new.env()\n\n\ndims2c_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\ndims2c_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2c_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2c_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2c_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"((double)({e1}) / (double)({e2}))\")\n# dividing integers truncates towards 0\ndims2c_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} / (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} % (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1}**{e2})\")\n\n\ndims2c <- function(dims, scope) {\n if (!length(dims) || identical(dims, list(1L))) {\n return(list(NULL, \"1\"))\n }\n\n syms <- as.character(unique(unlist(lapply(dims, all.vars))))\n\n syms <- mget(syms, scope, ifnotfound = syms) |>\n lapply(function(var) {\n if (is_size_name(var)) {\n return(as.character(var))\n }\n # resolve a variable from scope (i.e., some other arg var)\n if (!inherits(var, Variable))\n stop(\"could not resolve size: \", var)\n glue(\"Rf_asInteger({var@name})\")\n # Should this be as double?\n # TODO: force this into a named c var, to avoid repeated calls\n })\n\n eval_env <- list2env(syms, parent = dims2c_eval_base_env)\n c_dims <- lapply(dims, function(d) {\n if (inherits(d, Variable))\n return(glue(\"Rf_asInteger({d@name})\"))\n eval(d, eval_env)\n })\n\n c_dims\n}\n\nc_dims2c_len <- function(c_dims) {\n if (length(c_dims) == 1)\n c_dims[[1L]]\n else\n paste0(\"(\", unlist(c_dims), \")\", collapse = \" * \" )\n # eval(Reduce(\\(a, b) { call(\"*\", as.symbol(a@name), as.symbol(b@name)) }, dims),\n # eval_env)\n}\n\n\n# --- utils ----\n\nc_block <- function(...) {\n as_glue(paste0(c(\"{\", indent(c(...)), \"}\"), collapse = \"\\n\"))\n}\n\n# is_var_size <- function(x) inherits(x, VariableSize)\n\npasses_as_scalar <- function(var) {\n var@rank == 0 || var@rank == 1 && identical(var@dims, list(1L))\n}\n\npasses_as_value <- function(var) {\n passes_as_scalar(var) && isFALSE(var@modified)\n}\n\nsexptype <- function(mode) {\n switch(mode,\n integer = \"INTSXP\",\n double = \"REALSXP\",\n complex = \"CPLXSXP\",\n logical = \"LGLSXP\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nsexpdata <- function(mode) {\n switch(mode,\n integer = \"INTEGER\",\n double = \"REAL\",\n complex = \"COMPLEX\",\n logical = \"LOGICAL\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nis_size_name <- function(name) {\n if (is.symbol(name)) {\n name <- as.character(name)\n } else if (!is_string(name)) {\n return(FALSE)\n }\n\n grepl(\"(_len_|_dim_[0-9]+_)$\", name)\n}\n\nfriendly_size <- function(var, axis = NULL) {\n if (is.null(axis) || var@rank == 1 && axis == 1)\n glue(\"length({var@name})\")\n else\n glue(\"dim({var@name})[{axis}]\")\n}\n\nas_friendly_size_name <- function(size_name) {\n size_name <- as.character(size_name)\n if (endsWith(size_name, \"__len_\"))\n sprintf(\"length(%s)\", sub(\"__len_$\", \"\", size_name))\n else\n sub(\"^(.*)__dim_([0-9]+)_$\", \"dim(\\\\1)[\\\\2]\", size_name)\n}\n\nas_friendly_size_expression <- function(d) {\n stopifnot(is.call(d))\n nms <- all.names(d, functions = FALSE, unique = TRUE)\n friendly_substitutions <- new.env(parent = emptyenv())\n for(name in nms)\n if (is_size_name(name))\n assign(name, str2lang(as_friendly_size_name(name)), friendly_substitutions)\n d <- substitute_(d, friendly_substitutions)\n d <- call(\"(\", d)\n deparse1(d)\n}\n\nclosure_return_var_name <- function(closure) {\n return_var_name <- last(body(closure))\n if (!is.symbol(return_var_name))\n stop(\"return value must be a symbol\")\n as.character(return_var_name)\n}\n\n\nfsub_arg_var_c_type <- function(var) {\n type <- switch(var@mode,\n double = \"double*\",\n integer = \"int*\",\n complex = \"Rcomplex*\",\n logical = \"int*\",\n )\n\n # the first const declares that the pointed to values can't be modified\n # (the array values are read only)\n # the second const declares that the pointer itself can't be modified\n # (the fsub can never move/reallocate the array, so this const is always present)\n paste0(c(if (!var@modified) \"const\", type, \"const\"),\n collapse = \" \")\n}\n\nfsub_extern_decl <- function(fsub) {\n fsub_arg_names <- fsub@signature # arg names\n scope <- fsub@scope\n\n fsub_c_sig <- map_chr(fsub_arg_names, function(name) {\n if (is_size_name(name)) {\n type <- if (endsWith(\"__len_\", name))\n \"R_xlen_t\" else \"R_len_t\"\n glue(\"const {type} {name}\")\n } else {\n var <- get(name, fsub@scope)\n glue(\"{fsub_arg_var_c_type(var)} {var@name}__\")\n }\n })\n if (length(fsub_c_sig) >= 3L)\n fsub_c_sig <- paste0(\"\\n \", fsub_c_sig)\n\n glue(\"extern void {fsub@name}({str_flatten_commas(fsub_c_sig)});\")\n}\n"], ["/quickr/R/manifest.R", "\n\n\n### local variables with unspecified size are 'allocatable'. If they are bound\n### to a named symbol, the manifest must mark it as allocatable.\n###\n### Generally, if an expression produces an array of unspecified size, even if\n### it's never bound, it's still 'allocatable'. For example, an inline fortran\n### `pack()` call likely still produces a corresponding `malloc()` in the\n### generated code, regardless of if the output of `pack()` is bound to\n### a symbol (in the case of pack specifically, the malloc is behind a\n### _gfortran_pack() call.\n###\n### We can potentially link/mask `_malloc` and `_free` with a custom one that\n### uses R_alloc(), which will automatically free after the .External() call\n### returns. We can also pass along -fstack-arrays to gfortran and flang-new\n### (llvm), and that will mostly get rid most of the malloc calls, instead\n### allocating arrays on the C stack (which will automatically free on\n### return/lngjmp), but that will run into issues with larger arrays (especially\n### on windows)\n###\n### local vars of undefined sizes are allocatable. These will typically be\n### allocated on the c stack if they are not too large, but may include a\n### malloc+free call if they are large. Those might leak if we lngjmp\n### away (e.g., due to an interrupt). This potential leak is a non-issue for\n### now, since interrupts aren't supported yet, so there is no risk of lngjmp.\n###\n### When we do add support for interruptable quick functions, this potential\n### leak could be guarded against by:\n###\n### a) linking malloc -> R_alloc() for the fortran compilation unit which\n### would make the memory automatically be released after .External()\n### return. Note that unlinke malloc(), R_alloc() is not thread safe, so we would need\n### additional work for a `do concurrent` context to be supported.\n###\n### b) forcing all arrays to be stack allocated with -fstack-arrays passed\n### to the gfortran/flang-new. This is not a great, since c stack limits are\n### typically \"small\" and enforced by the OS.\n\nr2f.scope <- function(scope) {\n\n vars <- as.list.environment(scope, all.names = TRUE)\n vars <- lapply(vars, function(var) {\n\n intent_in <- var@name %in% names(formals(scope@closure))\n intent_out <- var@name == closure_return_var_name(scope@closure) || intent_in && var@modified\n\n intent <-\n if (intent_in && intent_out) \"intent(in out)\"\n else if (intent_in) \"intent(in)\"\n else if (intent_out) \"intent(out)\"\n else NULL\n\n type <- switch(var@mode,\n double = \"real(c_double)\",\n integer = \"integer(c_int)\",\n complex = \"complex(c_double_complex)\",\n logical = if (intent_in || intent_out) \"integer(c_int)\" else \"logical\",\n raw = \"integer(c_int8_t)\",\n stop(\"unrecognized kind: \", format(var))\n )\n\n dims <- if (passes_as_scalar(var)) {\n NULL\n } else {\n dims2f(var@dims, scope) |> str_flatten_commas() |> sprintf(fmt = \"(%s)\")\n }\n\n allocatable <- if (!is.null(dims) && grepl(\":\", dims, fixed = TRUE))\n \"allocatable\"\n\n if (intent_in && intent_out && !is.null(allocatable))\n stop(\"all input and output vars must have a fully defined shape\")\n\n name <- var@name\n comment <- if (var@mode == \"logical\") \" ! logical\"\n\n glue('{str_flatten_commas(type, intent, allocatable)} :: {name}{dims}{comment}',\n .null = \"\")\n })\n\n # vars that will be visible in the C bridge, either as an input or output\n non_local_var_names <- unique(c(names(formals(scope@closure)),\n closure_return_var_name(scope@closure)))\n\n # collect all size_names; sort so non-locals are declared first.\n size_names <- unique(unlist(lapply(non_local_var_names, function(name) {\n var <- scope[[name]]\n lapply(var@dims, all.names, functions = FALSE, unique = TRUE)\n }))) |> setdiff(names(formals(scope@closure)))\n\n sizes <- lapply(size_names, function(name) {\n kind <- if (endsWith(name, \"_len_\")) \"c_ptrdiff_t\" else \"c_int\"\n glue(\"integer({kind}), intent(in), value :: {name}\")\n })\n\n manifest <- compact(list(\n sizes = sizes,\n args = vars[non_local_var_names],\n locals = vars[setdiff(names(vars), non_local_var_names)]\n ))\n\n manifest <- imap(manifest, \\(declarations, category)\n str_flatten_lines(paste(\"!\", category), declarations)) |>\n str_flatten(\"\\n\\n\")\n\n manifest <- str_flatten_lines(\"! manifest start\", manifest, \"! manifest end\")\n\n # symbols that must come in as args to the subroutine\n # # method=\"radix\" for locale-independent stable order.\n signature <- unique(c(non_local_var_names, sort(size_names, method = \"radix\")))\n attr(manifest, \"signature\") <- signature\n\n manifest\n}\n\n\n\n## fortran precedence order\n## ** (exp)\n## * /\n## + -\n##\n## R prededence order\n## ^\n## - +\n## %/% %%\n## * /\n\n## generally, we just deparse() to convert an axis size.\n## except for NA, which becomes \":\"\n\ndims2f_eval_base_env <- new.env(parent = emptyenv())\ndims2f_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\n\n# any call always evaluates to a string.\n# every argument will be either:\n# - NA -> translates to \":\"\n# - a symbol -> translates to deparsed string\n# - a call ->\n\ndims2f_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2f_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2f_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2f_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"real({e1}) / real({e2})\")\n# dividing integers truncates towards 0\ndims2f_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"int({e1}) / int({e2})\")\ndims2f_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"mod(int({e1}), int({e2}))\")\ndims2f_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1})**({e2})\")\n\n\ndims2f <- function(dims, scope) {\n syms <- unique(unlist(lapply(dims, \\(d) if (is.language(d)) all.vars(d))))\n vars <- as.list(syms)\n names(vars) <- syms\n eval_env <- list2env(vars, parent = dims2f_eval_base_env)\n dims <- map_chr(dims, function(d) {\n d <- eval(d, eval_env)\n if (is.symbol(d)) as.character(d)\n else if (is_wholenumber(d)) as.character(d)\n else if (is_scalar_na(d)) \":\"\n else if (is_string(d)) d\n else if (inherits(d, Variable)) {\n # a locally allocated var that is a return var\n if (!d@modified && d@is_arg)\n return(d@name)\n stop(\"unexpected axis size value\")\n }\n })\n if (!length(dims) || identical(dims, \"1\")) \"\"\n else str_flatten_commas(dims)\n}\n\n"], ["/quickr/R/sizes.R", "\n\n\ncheck_type_call <- function(cl) {\n if (length(cl) > 2)\n stop(\"only one variable can be declared per type() call\")\n args <- as.list(cl)[-1]\n if (length(names(args)) != 1)\n stop(\"name must be provided as: type(<name> = <mode>(<<dims>>)\")\n if (!is.call(args[[1]]) && as.character(args[[1]]) %in% .atomic_type_names)\n stop(\"only atomic modes are supported\")\n}\n\n\ntype_call_to_var <- function(cl) {\n check_type_call(cl)\n Variable(\n name = names(cl)[-1],\n mode = as.character(cl[[2L]][[1L]]),\n dims = unname(as.list(cl[[2]])[-1])\n )\n}\n\nvar_to_type_call <- function(var) {\n arg <- as.call(c(as.symbol(var@mode), var@dims))\n arg <- setNames(list(arg), var@name)\n as.call(c(quote(type), arg))\n}\n\n\nget_flattened_args <- function(cl) {\n # flatten exprs from `{` in usage like declare({ ... })`\n args <- as.list(cl)[-1]\n args <- lapply(args, function(e) {\n if (is_missing(e))\n NULL\n else if (is_call(e, quote(`{`)))\n get_flattened_args(e)\n else\n list(e)\n })\n unlist(args, recursive = FALSE)\n}\n\nself_evaluate <- function(...) sys.call()\n\nsubstitute_declared_sizes <- function(e) {\n stopifnot(is_call(e, quote(`{`)))\n\n aliases <- new.env(parent = emptyenv())\n eval_env <- new.env(parent = emptyenv())\n for(name in all.names(e, functions = TRUE, unique = TRUE))\n assign(name, self_evaluate, eval_env)\n eval_env <- new.env(parent = eval_env)\n for(name in all.names(e, functions = FALSE, unique = TRUE))\n assign(name, as.symbol(name), eval_env)\n\n eval_env$`{` <- function(...) {\n as.call(c(list(quote(`{`)), list(...)))\n }\n\n eval_env$declare <- function(...) {\n args <- get_flattened_args(sys.call())\n args <- lapply(args, function(e) {\n if (is_type_call(e)) {\n var <- type_call_to_var(e)\n var@dims <- imap(var@dims, function(size, axis) {\n size_name <- as.symbol(get_size_name(var, axis))\n if (is.symbol(size) && !exists(size, aliases)) {\n # user defined implicit size_name alias\n assign(as.character(size), size_name, aliases)\n size <- size_name\n } else if (is_scalar_na(size)) {\n size <- size_name\n } else if (is_wholenumber(size)) {\n size <- as.integer(size)\n }\n size\n })\n e <- var_to_type_call(var)\n }\n e\n })\n\n as.call(c(quote(declare), args))\n }\n\n e <- eval(e, eval_env)\n\n # Now the 'aliases' env is populated; go through and substitute\n # size aliases with the actual size name.\n eval_env$declare <- function(...) {\n as.call(lapply(sys.call(), function(e) {\n if (is_type_call(e))\n e <- substitute_(e, aliases)\n e\n }))\n }\n\n eval(e, eval_env)\n\n}\n\n\nr2size <- function(r, scope) {\n typeof(r) |> switch(\n integer = r,\n double = {\n if (is_wholenumber(r))\n as.integer(r)\n else\n stop(\"size must be an integer, found: \", r)\n },\n symbol = {\n if (is_size_name(r))\n return(r)\n var <- get(r, scope)\n if (var@mode != \"integer\" || !passes_as_scalar(var))\n warning(\"size is not an integer:\", as.character(r))\n if (var@is_arg && !var@modified)\n return(r)\n # TODO: add specific unit tests here\n if (identical(var@r, r))\n return(r)\n # make a best effort to use the r expression last assigned to the\n # symbol, or fail gracefully and return NA.\n # closure-locals with unspecified shape are declared allocatable\n # input and/or output args with unspecified shape signal an error.\n r2size(var@r, scope)\n },\n language = {\n as.character(r[[1]]) |> switch(\n `+` = , `-` = , `/` = , `*` = , `^` = , `%/%` = , `%%` = {\n args <- as.list(r)[-1]\n args <- lapply(args, r2size, scope)\n if (anyNA(rapply(args, as.list)))\n return(NA_integer_)\n cl <- as.call(c(r[[1]], args))\n if (all(map_lgl(args, is.atomic)))\n cl <- eval(cl, baseenv())\n cl\n },\n length = {\n var <- get(r[[2L]], scope)\n if (var@rank == 1)\n return(var@dims[[1L]])\n len <- reduce(var@dims, \\(d1, d2) call(\"*\", d1, d2))\n r2size(len, scope)\n },\n `[` = {\n # [ only works when paired with dim()\n if (!is_call(r[[2L]], quote(dim)))\n return(NA_integer_)\n var <- get(r[[2L]][[2L]], scope)\n axis <- r[[3]]\n if (!is_wholenumber(axis))\n return(NA_integer_)\n if (axis > var@rank)\n stop(\"insufficient rank of variable in \", deparse1(r))\n var@dims[[axis]]\n },\n # dim = {\n #\n # },\n nrow = {\n var <- get(r[[2L]], scope)\n var@dims[[1]]\n },\n ncol = {\n var <- get(r[[2L]], scope)\n var@dims[[2]]\n },\n NA_integer_)\n },\n NA_integer_\n )\n}\n\nr2dims <- function(r, scope) {\n if (is.call(r)) {\n as.character(r[[1]]) |> switch(\n dim = {\n var <- get(r[[2L]], scope)\n return(var@dims)\n },\n c = {\n args <- lapply(r[-1], r2dims, scope)\n dims <- unlist(args, recursive = FALSE)\n return(as.list(dims))\n },\n r <- list(r))\n }\n lapply(r, r2size, scope)\n}\n\nget_size_name <- function(var, axis = NULL, name = var@name, rank = var@rank) {\n stopifnot(is.null(axis) || is_wholenumber(axis) && axis > 0)\n if (is.null(axis) || rank == 1 && axis == 1)\n sprintf(\"%s__len_\", name)\n else {\n if (axis > rank) stop(\"axis must not be > rank\")\n sprintf(\"%s__dim_%i_\", name, axis)\n }\n}\n\n\n\n# TODO: allow syntax like:\n# declare(type(a, b, c = integer(1)))\n# or:\n# declare(type(a = , b = , c = integer(1)))\n"], ["/quickr/R/subroutine.R", "\n\nnew_fortran_subroutine <- function(name, closure, parent = emptyenv()) {\n\n\n check_all_var_names_valid(closure)\n\n # translate body, and populate scope with variables\n body <- body(closure)\n\n # defuse calls like `-1` and `1+1i`. Not really necessary, but simplifies downstream a little.\n body <- defuse_numeric_literals(body)\n\n # TODO: try harder here to use one of the input vars as the output var\n body <- ensure_last_expr_sym(body)\n\n # update closure with sym return value\n base::body(closure) <- body\n # body <- rlang::zap_srcref(body)\n\n scope <- new_scope(closure, parent)\n\n # inject symbols for var sizes in declare calls, so like:\n # declare(type(foo = integer(nr, NA)),\n # type(bar = integer(nr, 3)))\n # become:\n # declare(type(foo = integer(foo_dim_1_, foo_dim_2_)),\n # type(bar = integer(foo_dim_1_, 3L)))\n body <- substitute_declared_sizes(body)\n body <- r2f(drop_last(body), scope)\n\n # check all input vars were declared\n # TODO: this check might be too late, because r2f() might throw cryptic errors\n # when handling undeclared variables. Either throw better errors from r2f(), or\n # handle all declares first\n for(arg_name in names(formals(closure))) {\n if (is.null(var <- get0(arg_name, scope)))\n stop(\"arg not declared: \", arg_name)\n }\n\n # figure out the return variable.\n if (is.symbol(last_expr <- last(body(closure)))) {\n return_var <- get(last_expr, scope)\n return_var@is_return <- TRUE\n scope[[as.character(last_expr)]] <- return_var\n } else {\n # lots we can still do here, just not implemented yet.\n stop(\"last expression in the function must be a bare symbol\")\n }\n\n manifest <- r2f.scope(scope)\n fsub_arg_names <- attr(manifest, \"signature\", TRUE)\n\n used_iso_bindings <- unique(unlist(use.names = FALSE, list(\n lapply(scope, function(var) {\n list(\n switch(\n var@mode,\n double = \"c_double\",\n integer = \"c_int\",\n logical = if (var@name %in% fsub_arg_names)\n \"c_int\",\n complex = \"c_double_complex\",\n raw = \"c_int8_t\"\n ),\n lapply(var@dims, function(size) {\n syms <- all.vars(size)\n c(if (any(grepl(\"__len_$\", syms))) \"c_ptrdiff_t\",\n if (any(grepl(\"__dim_[0-9]+_$\", syms))) \"c_int\")\n })\n )\n }))))\n\n # check for literal kinds\n if (!\"c_int\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+_c_int\\\\b\", body))\n append(used_iso_bindings) <- \"c_int\"\n }\n if (!\"c_double\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+\\\\.[0-9]+_c_double\\\\b\", body))\n append(used_iso_bindings) <- \"c_double\"\n }\n used_iso_bindings <- sort(used_iso_bindings, method = \"radix\")\n\n subroutine <- glue(\"\n subroutine {name}({str_flatten_commas(fsub_arg_names)}) bind(c)\n use iso_c_binding, only: {str_flatten_commas(used_iso_bindings)}\n implicit none\n\n {indent(manifest)}\n\n {indent(body)}\n end subroutine\n \")\n\n subroutine <- insert_fortran_line_continuations(subroutine)\n\n FortranSubroutine(\n subroutine,\n name = name,\n signature = fsub_arg_names,\n scope = scope,\n closure = closure\n )\n}\n\ninsert_fortran_line_continuations <- function(code, preserve_attributes = TRUE) {\n attrs_in <- attributes(code)\n\n code <- as.character(code)\n lines <- str_split_lines(code)\n lines <- trimws(lines, \"right\")\n\n if (any(too_long <- nchar(lines) > 132)) {\n # remove leading indentation\n lines[too_long] <- trimws(lines[too_long], \"left\")\n\n # move trailing comment at the end\n lines[too_long] <- sub(\"^(.*)!(.*)$\", \"!\\\\2\\n\\\\1\", lines[too_long])\n lines <- str_split_lines(lines)\n\n # maximum 255 continuations are allowed\n for (i in 1:256) {\n if (!any(too_long <- nchar(lines) > 132))\n break\n lines[too_long] <- sub(\"^(.{1,130})\\\\s\", \"\\\\1 &\\n\", lines[too_long])\n lines <- str_split_lines(lines)\n }\n if (i > 255L)\n stop(\"Too long line encountered. Please split long expressions into a sequence of smaller expressions.\")\n }\n\n code <- str_flatten_lines(lines)\n if (preserve_attributes)\n attributes(code) <- attrs_in\n code\n}\n\n"], ["/quickr/R/aaa-utils.R", "#' @importFrom glue glue glue_data trim as_glue glue_collapse single_quote\n#' @importFrom dotty .\n#' @importFrom stats setNames\n#' @importFrom utils gethash hashtab remhash sethash str\nNULL\n\n# @export\n# This will be exported by S7 next release.\n`:=` <- function(left, right) {\n name <- substitute(left)\n if (!is.symbol(name))\n stop(\"left hand side must be a symbol\")\n\n right <- substitute(right)\n if (!is.call(right))\n stop(\"right hand side must be a call\")\n\n if (is.symbol(cl <- right[[1L]]) &&\n as.character(cl) %in% c(\"function\", \"new.env\")) {\n # attach \"name\" attr for usage like:\n # foo := function(){}\n # foo := new.env()\n right <- eval(right, parent.frame())\n attr(right, \"name\") <- as.character(name)\n } else {\n # for all other usage,\n # inject name as a named arg, so that\n # foo := new_class(...)\n # becomes\n # foo <- new_class(..., name = \"foo\")\n\n right <- as.call(c(as.list(right), list(name = as.character(name))))\n\n ## skip check; if duplicate 'name' arg is an issue the call itself will signal an error.\n # if (hasName(right, \"name\")) stop(\"duplicate `name` argument.\")\n\n ## alternative code path that injects `name` as positional arg instead\n # right <- as.list(right)\n # right <- as.call(c(right[[1L]], as.character(name), right[-1L]))\n }\n\n eval(call(\"<-\", name, right), parent.frame())\n}\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\n`append<-` <- function(x, after, value) {\n if (missing(after))\n c(x, value)\n else\n append(x, value, after = after)\n}\n\n`append1<-` <- function (x, value) {\n stopifnot(is.list(x) || identical(mode(x), mode(value)))\n x[[length(x) + 1L]] <- value\n x\n}\n\n`prepend<-` <- function(x, value) {\n c(vector(typeof(x)), value, x)\n}\n\n`add<-` <- `+` #function(x, value) x + value\n\nmap_int <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = 0L, ...)\nmap_lgl <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)\nmap_chr <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = \"\", ...)\n\nimap <- function (.x, .f, ...) {\n out <- .mapply(.f, list(.x, names(.x) %||% seq_along(.x)),\n list(...))\n names(out) <- names(.x)\n out\n}\n\nmap2 <- function (.x, .y, .f, ...) {\n if (length(.x) != length(.y) && length(.x) != 1L && length(.y) != 1L)\n stop(\".x and .y must have the same length, or one of them must have length 1\")\n out <- .mapply(.f, list(.x, .y), list(...))\n if (length(.x) == length(out))\n names(out) <- names(.x)\n out\n}\n\ndiscard <- function(.x, .f, ...)\n .x[!vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\nkeep <- function(.x, .f, ...)\n .x[vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\ncompact <- function(.x)\n .x[as.logical(lengths(.x, use.names = FALSE))]\n\ndrop_nulls <- function(x, i) {\n if (missing(i))\n x[!vapply( X = x, FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)]\n else {\n drop <- logical(length(x))\n names(drop) <- names(x)\n drop[i] <- vapply(X = x[i], FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)\n x[!drop]\n }\n}\n\nlast <- function(x) x[[length(x)]]\ndrop_last <- function(x) x[-length(x)]\n\nis_scalar_na <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && is.na(x)\nis_scalar_atomic <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_scalar_integer <- function(x) is.integer(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_string <- function(x) is.character(x) && length(x) == 1L && !is.na(x) # could also be 'glue' class.\nis_bool <- function(x) is.logical(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_number <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_wholenumber <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x) &&\n x >= 0L && (is.integer(x) || is.double(x) && trunc(x) == x)\n\nnew_function <- function(args = NULL, body = NULL, env = parent.frame()) {\n as.function.default(c(args, body %||% list(NULL)), env)\n}\n\nis_call <- function(x, name = NULL) {\n is.call(x) && (is.null(name) || identical(as.symbol(name), x[[1L]]))\n}\n\nstr_flatten <- function(x, collapse = \"\") {\n paste0(as.character(unlist(x, use.names = FALSE)), collapse = collapse)\n}\n\nstr_flatten_lines <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \"\\n\")\n}\n\nstr_flatten_commas <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \", \")\n}\n\nstr_flatten_args <- function(..., multiline = length(dots) >= 3) {\n dots <- unlist(c(character(), ...), use.names = FALSE)\n if (multiline) {\n dots <- paste0(\"\\n \", dots, collapse = \",\")\n paste(dots, \"\\n\")\n } else {\n paste0(dots, collapse = \",\")\n }\n}\n\ninterleave <- function(x, y) {\n stopifnot(is.atomic(x), is.atomic(y), length(y) == 1L, typeof(x) == typeof(y))\n drop_last(as.vector(rbind(x, y, deparse.level = 0L)))\n}\n\nstr_split_lines <- function(...) {\n x <- c(...) |>\n unlist(use.names = FALSE) |>\n strsplit(\"\\n\", fixed = TRUE)\n x[!lengths(x)] <- \"\"\n x |>\n unlist(use.names = FALSE) |>\n trimws(\"right\")\n}\n\nindent <- function(x, n = 2L) {\n x <- str_split_lines(x)\n x <- sub(\"[ \\t\\r]+$\", \"\", x, perl = TRUE) # trim trailing whitespace\n paste0(strrep(\" \", n), x, collapse = \"\\n\")\n}\n\nparent.pkg <- function(env = parent.frame(2)) {\n if (isNamespace(env <- topenv(env)))\n as.character(getNamespaceName(env)) # unname\n else\n NULL # print visible\n}\n\nset_names <- function(x, nm = x, ...) {\n names(x) <- as.character(\n if (is.function(nm)) nm(names(x), ...)\n else unlist(list(nm, ...), use.names = FALSE)\n )\n x\n}\n\nzip_lists <- function(...) {\n x <- if (...length() == 1L) ..1 else list(...)\n\n if (is.character(nms.1 <- names(x.1 <- x[[1L]])))\n if (anyDuplicated(nms.1) || anyNA(nms.1) || any(nms.1 == \"\"))\n stop(\"All names must be unique.\",\n \" (Use `unname()` for positional matching.)\")\n\n if (length(setdiff(lengths(x), 1L)) != 1L)\n stop(\"all elements must have the same length\")\n\n for (i in seq_along(x)) {\n if (identical(nms.1, nms.i <- names(x[[i]])))\n next\n if (setequal(nms.1, nms.i)) {\n x[[i]] <- x[[i]][nms.1]\n next\n }\n stop(\"All names of arguments provided to `zip_lists()` must match.\",\n \" Call `unname()` on each argument if you want positional matching\")\n }\n ans <- .mapply(list, x, NULL)\n names(ans) <- nms.1\n ans\n}\n\nis_missing <- function(x) missing(x) || identical(x, quote(expr = ))\n\nis_type_call <- function(e) {\n is.call(e) && identical(e[[1]], quote(type))\n}\n\nreduce <- function (.x, .f, ..., .init) {\n f <- function(x, y) .f(x, y, ...)\n Reduce(f, .x, init = .init)\n}\n\nsubstitute_ <- function(expr, env) {\n do.call(base::substitute, list(expr, env))\n}\n\ndefer <- function (expr, env = parent.frame(), after = FALSE) {\n thunk <- as.call(list(function() expr))\n do.call(on.exit, list(thunk, TRUE, after), envir = env)\n}\n\nis_scalar <- function(x) identical(length(x), 1L)\n"], ["/quickr/R/classes.R", "#' @import S7\nNULL\n\nnew_setter <- function(coerce = NULL, coerce_null = FALSE, set_once = FALSE, env = parent.frame(2L)) {\n\n if (is.null(coerce) || isFALSE(coerce) && isFALSE(set_once))\n return()\n\n bind_name <- quote(name <- as.character(last(attr(self, \".setting_prop\", TRUE))))\n\n check_set_once <- if (set_once) {\n quote(if (!is.null(prop(self, name)))\n stop(name, \" can only be set once\"))\n }\n\n rebind_coerced_value <-\n if (is.null(coerce) || isFALSE(coerce)) {\n NULL\n } else if (isTRUE(coerce)) {\n quote(value <- convert(\n from = value,\n to = S7_class(self)@properties[[as.character(name)]]$class\n ))\n } else if (is.function(coerce) || is.symbol(coerce)) {\n bquote(value <- .(coerce)(value))\n } else if (is.language(coerce)) {\n bquote(value <- .(coerce))\n } else {\n stop(\"coerce must be TRUE, FALSE, NULL, a function, a symbol, or a call\")\n }\n\n if (!coerce_null && !is.null(rebind_coerced_value)) {\n rebind_coerced_value <- bquote(if (!is.null(value)) .(rebind_coerced_value))\n }\n\n set <- quote(`prop<-`(\n object = self,\n name = name,\n check = FALSE,\n value = value\n ))\n\n new_function(\n args = alist(self = , value = ),\n body = as.call(c(quote(`{`),\n bind_name,\n check_set_once,\n rebind_coerced_value,\n set)),\n env = env\n )\n}\n\n\nnew_scalar_validator <- function(allow_null = FALSE,\n allow_na = FALSE,\n additional_checks = NULL,\n env = parent.frame(2L)) {\n checks <- c(\n if (allow_null) quote(if (is.null(value)) return()),\n quote(if (length(value) != 1L) return(\"must be a scalar\")),\n if (!allow_na) quote(if (anyNA(value)) return(\"must not be NA\")),\n additional_checks\n )\n\n new_function(\n args = alist(value = ),\n body = as.call(c(quote(`{`), checks)),\n env = parent.frame(2L)\n )\n}\n\n\nprop_bool <- function(default, allow_null = FALSE, allow_na = FALSE, set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n new_property(\n class = if (allow_null) NULL | class_logical else class_logical,\n setter = new_setter(set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null,\n allow_na = allow_na),\n default = default\n )\n}\n\n\nprop_string <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = FALSE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(as.character)\n\n new_property(\n class = if (allow_null) NULL | class_character else class_character,\n default = default,\n validator = new_scalar_validator(allow_null = allow_null),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once)\n )\n}\n\n\nprop_wholenumber <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = TRUE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(\n if (is_wholenumber(value)) as.integer(value)\n else stop(\"@\", name, \" must be a whole number, but received: \", value)\n )\n\n new_property(\n class = if (allow_null) NULL | class_integer else class_integer,\n default = as.integer(default),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null)\n )\n}\n\n\nprop_enum <- function(values,\n nullable = FALSE,\n default = if (nullable) NULL else values[1],\n exact = FALSE,\n set_once = FALSE) {\n\n stopifnot(\n \"values must be a character vector of length >= 2 without any NA\" =\n is.character(values) && length(values) >= 2 && !anyNA(values)\n )\n\n coerce <- if (exact) NULL else {\n bquote(if (length(value) == 1L && !anyNA(i <- charmatch(value, .(values))))\n .(values)[i] else value)\n }\n\n display_values <- glue_collapse(single_quote(values), sep = \", \", last = \", or \")\n msg <- sprintf(\"must be either %s, not '\", display_values)\n validator <- new_scalar_validator(allow_null = nullable,\n additional_checks = bquote(\n if (!match(value, .(values), nomatch = 0L))\n return(paste0(.(msg), value, \"'.\"))\n ))\n\n new_property(\n class = if (nullable) NULL | class_character else class_character,\n setter = new_setter(coerce = coerce, coerce_null = !nullable, set_once = set_once),\n validator = validator,\n default = default\n )\n}\n\n\n.atomic_type_names <- c(\"integer\", \"logical\", \"double\",\n \"character\", \"raw\", \"complex\")\n\n\n# the print method for this should only print non-null values\nVariable := new_class(\n properties = list(\n\n mode = prop_enum(.atomic_type_names, nullable = TRUE, set_once = FALSE),\n\n dims = new_property(\n # NULL means scalar\n NULL | class_list,\n setter = function(self, value) {\n if (!length(value))\n return(self)\n\n value <- switch(typeof(value),\n logical = , integer = , double = as.list(value),\n language = , symbol = list(value), # implicit rank-1\n list = value,\n stop(\"@dims must be a list\")\n )\n\n value <- lapply(value, \\(axis) {\n if (is.language(axis)) {\n axis\n } else if (is_wholenumber(axis) || is_scalar_na(axis)) {\n as.integer(axis)\n } else {\n stop(sprintf(\n \"%s@dims must be a list of language or scalar integers, not %s\",\n self@name %||% '', axis\n ))\n }\n })\n\n self@dims <- value\n self\n } # dims$setter\n ), # dims = new_property()\n\n name = prop_string(\n allow_null = TRUE,\n coerce = quote(switch(typeof(value), symbol = as.character(value), value)),\n set_once = FALSE #TRUE\n ),\n\n rank = new_property(\n class_integer,\n getter = function(self) {\n length(self@dims)\n }),\n\n modified = prop_bool(default = FALSE),\n\n r = new_property(\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n # custom setter to workaround https://github.com/RConsortium/S7/issues/511\n attr(self, \"r\") <- value\n self\n }\n ),\n\n is_arg = prop_bool(default = FALSE),\n\n is_return = prop_bool(default = FALSE),\n\n # TRUE for closure args and return values, FALSE for all other vars.\n is_external = new_property(\n class_logical,\n getter = function(self)\n self@is_arg || self@is_return\n ),\n\n is_scalar = new_property(\n class_logical,\n getter = function(self) {\n self@rank == 0 || identical(self@dims, list(1L))\n }\n )\n\n )\n)\n\n# method(print, Variable) <- function(x, ...) {\n#\n# }\n\n\n\nFortran := new_class(\n class_character,\n\n properties = list(\n\n value = NULL | Variable,\n\n r = new_property(\n # custom setter only to workaround https://github.com/RConsortium/S7/issues/511\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n attr(self, \"r\") <- value\n self\n }\n )\n ),\n\n validator = function(self) {\n if (length(self) != 1L)\n \"must be a length 1 string\"\n }\n)\n\n\nFortranSubroutine := new_class(Fortran, properties = list(\n name = prop_string(),\n signature = class_character,\n closure = class_function,\n scope = NULL | class_environment,\n c_bridge = S7::new_property(\n NULL | class_character,\n getter = function(self) {\n make_c_bridge(self) %error% NULL\n })\n))\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\ntry_prop <- function(object, name) S7::prop(object, name) %error% NULL\n\nemit <- function(..., sep = \"\", end = \"\\n\") cat(..., end, sep = sep)\n\nmethod(format, Variable) <- function(x, ...) {\n capture.output(str(x))\n}\n\nmethod(as.character, Variable) <- function(x, ...)\n x@name %||% stop(\"Variable does not have a name\")\n\nmethod(print, Fortran) <- function(x, ...) {\n emit(trimws(x), end = \"\\n\\n\")\n for(prop_name in c(\"value\", \"r\", \"c_bridge\"))\n if (!is.null(prop_val <- try_prop(x, prop_name))) {\n emit(\"@\", prop_name, \": \", trimws(indent(format(prop_val))));\n }\n}\n"], ["/quickr/R/quick.R", "#' Compile a Quick Function\n#'\n#' Compile an R function.\n#'\n#' @param fun An R function\n#' @param name Optional string, name to use for the function.\n#'\n#' @details\n#'\n#' ## `declare(type())` syntax:\n#'\n#' The shape and mode of all function arguments must be declared. Local and\n#' return variables may optionally also be declared.\n#'\n#' `declare(type())` also has support for declaring size constraints, or size\n#' relationships between variables. Here are some examples of declare calls:\n#'\n#' ```r\n#' declare(type(x = double(NA))) # x is a 1-d double vector of any length\n#' declare(type(x = double(10))) # x is a 1-d double vector of length 10\n#' declare(type(x = double(1))) # x is a scalar double\n#'\n#' declare(type(x = integer(2, 3))) # x is a 2-d integer matrix with dim (2, 3)\n#' declare(type(x = integer(NA, 3))) # x is a 2-d integer matrix with dim (<any>, 3)\n#'\n#' # x is a 4-d logical matrix with dim (<any>, 24, 24, 3)\n#' declare(type(x = logical(NA, 24, 24, 3)))\n#'\n#' # x and y are 1-d double vectors of any length\n#' declare(type(x = double(NA)),\n#' type(y = double(NA)))\n#'\n#' # x and y are 1-d double vectors of the same length\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' # x and y are 1-d double vectors, where length(y) == length(x) + 2\n#' declare(type(x = double(n)),\n#' type(y = double(n+2)))\n#' ```\n#'\n#' You can provide declarations to `declare()` as:\n#'\n#' - Multiple arguments to a single `declare()` call\n#' - Separate `declare()` calls\n#' - Multiple arguments within a code block (`{}`) inside `declare()`\n#'\n#' ```r\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' declare(type(x = double(n)))\n#' declare(type(y = double(n)))\n#'\n#' declare({\n#' type(x = double(n))\n#' type(y = double(n))\n#' })\n#' ```\n#'\n#' ## Return values\n#'\n#' The shape and type of a function return value must be known at compile time.\n#' In most situations, this will be automatically inferred by `quick()`. However,\n#' if the output is dynamic, then you may need to provide a hint.\n#' For example, returning the result of `seq()` will fail because the output shape\n#' cannot be inferred.\n#'\n#' ```r\n#' # Will fail to compile:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' ```\n#'\n#' However, if the output size can be declared as a dynamic expression using other\n#' values known at runtime, compilation will succeed:\n#'\n#' ```r\n#' # Succeeds:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' type(out = integer(end - start + 1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' quick_seq(1L, 5L)\n#' ```\n#'\n#' @returns A quicker R function.\n#' @export\n#' @examples\n#' add_ab <- quick(function(a, b) {\n#' declare(type(a = double(n)),\n#' type(b = double(n)))\n#' out <- a + b\n#' out\n#' })\n#' add_ab(1, 2)\nquick <- function(fun, name = NULL) {\n if (is.null(name)) {\n name <- if (is.symbol(substitute(fun)))\n deparse(substitute(fun))\n else\n make_unique_name(prefix = \"anonymous_quick_function_\")\n }\n\n if (nzchar(pkgname <- Sys.getenv(\"DEVTOOLS_LOAD\"))) {\n if (!collector$is_active()) {\n if (!requireNamespace(\"pkgload\", quietly = TRUE)) {\n stop(\"Please install 'pkgload'\")\n }\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_code)) {\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n defer(dump_collected(), sys.frame(i), after = TRUE)\n break\n }\n }\n }\n }\n\n if (collector$is_active()) {\n # we are in a quickr::compile_package() or a devtools::load_all() call,\n # merely collecting functions at this point.\n quick_closure <- create_quick_closure(name, fun)\n collector$add(name = name, closure = fun, quick_closure = quick_closure)\n return(quick_closure)\n }\n\n pkgname <- parent.pkg()\n if (!is.null(pkgname) && pkgname != \"quickr\") {\n # we are in a package - but outside a quickr::compile_package() call.\n return(create_quick_closure(name, fun))\n }\n\n # not in a package. Compile and load eagerly.\n attr(fun, \"name\") <- name\n fun <- compile(r2f(fun))\n attr(fun, \"name\") <- NULL\n\n fun\n}\n\ncompile <- function(fsub, build_dir = tempfile(paste0(fsub@name, \"-build-\"))) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n name <- fsub@name\n c_wrapper <- make_c_bridge(fsub)\n\n if (dir.exists(build_dir)) unlink(build_dir, recursive = T)\n if (!dir.exists(build_dir))\n dir.create(build_dir)\n owd <- setwd(build_dir)\n on.exit(setwd(owd))\n\n fsub_path <- paste0(name, \"_fsub.f90\")\n c_wrapper_path <- paste0(name, \"_c_wrapper.c\")\n dll_path <- paste0(name, .Platform$dynlib.ext)\n writeLines(fsub, fsub_path)\n writeLines(c_wrapper, c_wrapper_path)\n\n suppressWarnings({\n result <- system2(\n R.home(\"bin/R\"),\n c(\"CMD SHLIB --use-LTO\", \"-o\", dll_path, fsub_path, c_wrapper_path),\n stdout = TRUE, stderr = TRUE\n )\n })\n if (!is.null(attr(result, \"status\"))) {\n writeLines(result, stderr())\n str(attributes(result))\n stop(\"Compilation Error\")\n }\n\n # tryCatch(dyn.unload(dll_path), error = identity)\n dll <- dyn.load(dll_path)\n c_wrapper_name <- paste0(fsub@name, \"_\")\n ptr <- getNativeSymbolInfo(c_wrapper_name, dll)$address\n\n create_quick_closure(fsub@name, fsub@closure, native_symbol = ptr)\n}\n\n\n\ncreate_quick_closure <- function(name, closure,\n native_symbol = as.name(paste0(name, \"_\"))) {\n body(closure) <- as.call(c(quote(.External), native_symbol,\n lapply(names(formals(closure)), as.name)))\n closure\n}\n\n\n\ncheck_all_var_names_valid <- function(fun) {\n nms <- unique(c(names(formals(fun)), all.vars(body(fun), functions = FALSE)))\n invalid <- endsWith(nms, \"_\") | startsWith(nms, \"_\") | nms %in% c(\n\n # clashes with Fortran subroutine symbols\n \"c_int\", \"c_double\", \"c_ptrdiff_t\",\n\n # clashes with C bridge symbols\n \"int\" #, \"double\",\n\n # ??? (clashes with R symbols?)\n # \"double\", \"integer\"\n )\n if (any(invalid)) {\n stop(\"symbols cannot start or end with '_', but found: \",\n glue_collapse(invalid, \", \", last = \", and \"))\n }\n}\n\n\n\n# ---- utils ----\n\nmake_unique_name <- local({\n i <- 0L\n function(prefix = \"tmp\") {\n paste0(prefix, i <<- i + 1L)\n }\n})\n"], ["/quickr/R/compile-package.R", "\n\n\n#' Compile all `quick()` functions in a package.\n#'\n#' This will compile all `quick()` functions in an R package, and\n#' generate source files in the `src/` directory.\n#'\n#' Note, this function is automatically invoked during a `pkgload::load_all()` call.\n#'\n#' @param path Path to an R package\n#'\n#' @returns Called for its side effect.\n#' @export\ncompile_package <- function(path = \".\") {\n if (path != \".\") {\n owd <- setwd(path)\n on.exit(setwd(owd), add = TRUE)\n }\n\n if (!dir.exists(\"R\") || !file.exists(\"DESCRIPTION\"))\n stop(path, \" does not appear to be an R package.\")\n\n pkgname <- read.dcf(\"DESCRIPTION\", \"Package\")\n if (length(pkgname) != 1)\n stop(sprintf(\"path '%s' does not point to an R package\", path))\n pkgname <- as.character(pkgname)\n\n # collect all `quick()` calls in the package\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n\n # TODO: need to unset various R_* env vars, or just\n # take a dep on callr\n system2(file.path(R.home(\"bin\"), \"R\"),\n c(\"-q\", \"-e\", shQuote(\"pkgload::load_all()\")))\n}\n\n\ndump_collected <- function() {\n\n collected <- collector$get_collected()\n\n # try to resolve closure names for anonymous functions\n pkg_ns <- topenv(environment(collected[[1L]]$closure))\n pkg_funcs <- as.list.environment(pkg_ns, all.names = TRUE)\n tab <- hashtab(\"address\", length(collected))\n for (i in seq_along(pkg_funcs)) {\n if (typeof(fn <- pkg_funcs[[i]]) == \"closure\")\n # if is quick closure ...\n sethash(tab, pkg_funcs[[i]], names(pkg_funcs)[i])\n }\n\n quick_funcs <- unlist(recursive = FALSE, lapply(collected, function(x) {\n if (!startsWith(x$name, \"anonymous_quick_function_\"))\n return(setNames(list(x$closure), x$name))\n true_name <- gethash(tab, x$quick_closure)\n if (is.null(true_name))\n return(setNames(list(x$closure), x$name))\n # update pkg_ns with true name\n quick_closure <- create_quick_closure(true_name, x$closure)\n pkg_ns[[true_name]] <- quick_closure\n remhash(tab, x$quick_closure)\n setNames(list(x$closure), true_name)\n }))\n\n\n pkgname <- basename(normalizePath(\".\"))\n\n # check if we have a useDynLib line in NAMESPACE.\n if (!any(sapply(parse(file = \"NAMESPACE\"), function(e) {\n identical(e[[1]], quote(useDynLib)) && isTRUE(e$.registration)\n })))\n message(\"- Please add this roxygen directive somewhere in the Package R sources:\\n \",\n glue(\"#' @useDynLib {pkgname}, .registration = TRUE\"), \"\\n\",\n \"- Then run `devtools::document()`\\n\")\n\n sources <- zip_lists(imap(quick_funcs, function(func, name) {\n fsub <- new_fortran_subroutine(name, func)\n cbridge <- make_c_bridge(fsub, headers = name == names(quick_funcs)[1])\n list(f90 = fsub, c = cbridge)\n })) |> lapply(\\(x) x |> unlist() |> interleave(\"\\n\"))\n\n entries <- paste0(sprintf(' {\"%1$s\", (DL_FUNC) &%1$s, -1}',\n paste0(names(quick_funcs), \"_\")),\n collapse = \",\\n\")\n entries <- sprintf(\"static const R_ExternalMethodDef QuickrEntries[] = {\\n%s\\n};\",\n entries)\n\n append(sources$c) <- c(\"\", entries, \"\")\n\n R_init_pkg <- paste0(\"R_init_\", pkgname, \"(\")\n has_pkg_init_fn <- list.files(\"src\", pattern = \"\\\\.(c|cpp|h|hpp|c\\\\+\\\\+)$\",\n recursive = TRUE, all.files = TRUE,\n full.names = TRUE) |>\n setdiff(\"src/quickr_entrypoints.c\") |>\n lapply(function(f) {\n any(grepl(R_init_pkg, readLines(f, warn = FALSE), fixed = TRUE))\n }) |> unlist() |> any()\n\n append(sources$c) <- c(\"#include <R_ext/Rdynload.h>\", \"\")\n\n init_fn <- if (has_pkg_init_fn) {\n glue(\"\n void R_init_{pkgname}_quick_functions(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n }}\")\n } else {\n init_pkgname <- gsub(\".\", \"_\", pkgname, fixed = TRUE)\n glue(\"\n void R_init_{init_pkgname}(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n R_useDynamicSymbols(dll, FALSE);\n }}\")\n }\n\n append(sources$c) <- init_fn\n\n sources <- lapply(sources, str_split_lines)\n\n src_files_written <- FALSE\n if (!file.exists(\"src\")) dir.create(\"src\")\n cbridges_filepath <- \"src/quickr_entrypoints.c\"\n if (!file.exists(cbridges_filepath) || !identical(sources$c, readLines(cbridges_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(cbridges_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$c, cbridges_filepath)\n cli::cli_inform(c(i = \"Updated {.file {cbridges_filepath}}\"))\n src_files_written <- TRUE\n }\n\n fsubs_filepath <- \"src/quickr_sub_routines.f90\"\n if (!file.exists(fsubs_filepath) || !identical(sources$f90, readLines(fsubs_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(fsubs_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$f90, fsubs_filepath)\n cli::cli_inform(c(i = \"Updated {.file {fsubs_filepath}}\"))\n src_files_written <- TRUE\n }\n\n if (src_files_written) {\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_all)) {\n defer(pkgload::load_all(), sys.frame(i), after = TRUE)\n rlang::return_from(sys.frame(i), value = invisible())\n break\n }\n }\n }\n invisible()\n}\n\npkg_dll_path <- function (pkgname) {\n file.path(\"src\", paste0(pkgname, .Platform$dynlib.ext))\n}\n\n\ncollector <- local({\n\n .collected <- NULL\n\n activate <- function(name = NULL) {\n .collected <<- list()\n attr(.collected, \"name\") <<- name\n }\n\n is_active <- function() {\n is.list(.collected)\n }\n\n add <- function(...) {\n .collected[[length(.collected)+1L]] <<- list(...)\n }\n\n get_collected <- function(clear = TRUE) {\n if (clear)\n on.exit(.collected <<- NULL)\n .collected\n }\n\n environment()\n})\n"], ["/quickr/R/scope.R", "\n\nnew_ordered_env <- function(parent = emptyenv()) {\n env <- new.env(parent = parent)\n class(env) <- \"quickr_ordered_env\"\n env\n}\n\n#' @export\n`[[<-.quickr_ordered_env` <- function(x, name, value) {\n attr(x, \"ordered_names\") <- unique(c(attr(x, \"ordered_names\", TRUE), name))\n assign(name, value, envir = x)\n x\n # NextMethod()\n}\n\n#' @export\n`[[.quickr_ordered_env` <- function(x, name) {\n get0(name, x) # name can be a symbols too\n}\n\n#' @export\nnames.quickr_ordered_env <- function(x) {\n all_names <- ls(envir = x, sorted = FALSE)\n ordered_names <- attr(x, \"ordered_names\", TRUE)\n if (!setequal(all_names, ordered_names)) {\n warning(\"untracked name\")\n stop(\"untracked name\")\n }\n ordered_names\n}\n\n#' @export\nas.list.quickr_ordered_env <- function(x, ...) {\n out <- as.list.environment(x, all.names = TRUE, ...)\n out[names.quickr_ordered_env(x)]\n}\n\n#' @export\nprint.quickr_ordered_env <- function(x, ...) {\n emit(\"env (class: \", str_flatten_commas(class(x)), \") with bindings:\")\n str(as.list.quickr_ordered_env(x), no.list = TRUE)\n}\n\n\ncheck_assignment_compatible <- function(target, value) {\n if (is.null(value)) return()\n stopifnot(exprs = {\n inherits(target, Variable)\n inherits(value, Variable)\n passes_as_scalar(target) || passes_as_scalar(value) || target@rank == value@rank\n })\n}\n\nnew_scope <- function(closure, parent = emptyenv()) {\n scope <- new_ordered_env(parent = parent)\n class(scope) <- unique(c(\"quickr_scope\", class(scope)))\n attr(scope, \"closure\") <- closure\n\n\n attr(scope, \"get_unique_var\") <- local({\n i <- 0L\n function(...) {\n name <- paste0(\"tmp\", i <<- i + 1L, \"_\")\n (scope[[name]] <- Variable(..., name = name))\n }\n })\n attr(scope, \"assign\") <- function(name, value) {\n stopifnot(inherits(value, Variable), is.symbol(name) || is_string(name))\n name <- as.character(name)\n if (exists(name, scope))\n check_assignment_compatible(get(name, scope), value)\n value@name <- name\n assign(name, value, scope)\n }\n scope\n}\n\n\n#' @export\n`@.quickr_scope` <- function(x, name) attr(x, name, exact = TRUE)\n\n#' @export\n`@<-.quickr_scope` <- function(x, name, value) `attr<-`(x, name, value = value)\n\n#' @importFrom utils .AtNames findMatches\n#' @export\n.AtNames.quickr_scope <- function(x, pattern = \"\")\n findMatches(pattern, names(attributes(x)))\n\n"], ["/quickr/R/preprocess-lang.R", "\n\ndefuse_numeric_literals <- function(e) {\n if (is.call(e)) {\n e <- as.call(lapply(e, defuse_numeric_literals))\n if (is.symbol(e1 <- e[[1L]]) &&\n as.character(e1) %in% c(\"+\", \"-\", \"*\", \"/\", \"%%\", \"%/%\", \"^\") &&\n all(map_lgl(e[-1L], is.atomic))) {\n e <- eval(e, baseenv())\n }\n }\n e\n}\n\n\nensure_last_expr_sym <- function(bdy) {\n if (!is_call(bdy, quote(`{`)))\n stop(\"bad body, needs {\")\n if (!is.symbol(last_expr <- last(bdy))) {\n bdy[[length(bdy)]] <- call(\"<-\", quote(out_), last_expr)\n bdy[[length(bdy) + 1L]] <- quote(out_)\n }\n bdy\n}\n\n\nwhole_doubles_to_ints <- function(x) {\n walker <- function(x) {\n switch(\n typeof(x),\n double = if (trunc(x) == x) as.integer(x),\n language = as.call(lapply(x, walker)),\n list = lapply(x, walker),\n x\n )\n }\n walker(x)\n}\n"], ["/quickr/R/zzz.R", "# # ' @export\n# `@.default` <- function(x, name) {\n# if (isS4(x))\n# methods::slot(x, name)\n# else\n# attr(x, name, TRUE)\n# }\n#\n# # ' @export\n# `@<-.default` <- function(x, name, value) {\n# if (isS4(x))\n# methods::`slot<-`(x, name, value = value)\n# else\n# `attr<-`(x, name, value)\n# }\n#\n# # ' @importFrom utils .AtNames findMatches\n# .AtNames.default <- function(x, pattern = \"\") {\n# if (isS4(x))\n# findMatches(pattern, methods::slotNames(x))\n# else\n# findMatches(pattern, names(attributes(x)))\n# }\n#\n# on_load_register_.AtNames.default <- function() {\n# # if we register via NAMESPACE, we get warning\n# # about overwriting utils:::.AtNmaes.default\n# registerS3method(\".AtNames\", \"default\", .AtNames.default)\n# }\n\n.onLoad <- function(...) {\n S7::methods_register()\n asNamespace(\"dotty\")$dotify()\n # on_load_register_.AtNames.default()\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-21 01:15:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(args, scope, ..., hoist_mask = function(mask) FALSE) {}", "code_description": "This code segment functions to: Translate array indexing operations by processing subscript expressions, handling logical and integer indices, converting missing arguments to full range selectors, and generating appropriate Fortran array access syntax while managing dimension preservation rules."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nr2f_handlers[[\"[\"]] <- function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n # Handle array subsetting syntax\n array_expr <- r2f(args[[1]], scope, ...)\n indices <- lapply(args[-1], function(idx) {\n if (is_missing(idx)) {\n # Empty index means whole dimension in Fortran\n return(Fortran(\":\"))\n }\n r2f(idx, scope, ...)\n })\n \n # Handle different dimension cases\n index_str <- str_flatten_commas(indices)\n fortran_code <- glue(\"{array_expr}({index_str})\")\n \n # Determine output dimensions\n original_dims <- array_expr@value@dims\n new_dims <- if (length(indices) == 1 && array_expr@value@rank > 1) {\n # Single index for multidimensional array becomes vector\n list(original_dims[[1]] * original_dims[[2]])\n } else {\n # Preserve remaining dimensions\n original_dims[-seq_along(indices)]\n }\n \n Fortran(fortran_code, Variable(array_expr@value@mode, new_dims))\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-16-22"}, "editdistance_info": {"edit_distance": 13.2812, "calculate_time": "2025-08-21 01:16:22", "true_code_clean": "function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n var <- args[[1]]\n var <- r2f(var, scope, ...)\n idxs <- whole_doubles_to_ints(args[-1])\n idxs <- imap(idxs, function(idx, i) {\n if (is_missing(idx))\n Fortran(\":\", Variable(\"integer\", var@value@dims[[i]]))\n else\n r2f(idx, scope, ...)\n })\n if (length(idxs) == 1 &&\n idxs[[1]]@value@mode == \"logical\" &&\n idxs[[1]]@value@rank == var@value@rank) {\n mask <- idxs[[1]]\n if (hoist_mask(mask))\n return(var)\n return(Fortran(glue(\"pack({var}, {mask})\"), Variable(var@value@mode, dims = NA)))\n }\n if (length(idxs) != var@value@rank)\n stop(\"number of args to x[...] must match the rank of x, received:\",\n deparse1(as.call(c(quote(`[`,args )))))\n drop <- args$drop %||% TRUE\n idxs <- lapply(idxs, function(subscript) {\n switch(\n paste0(subscript@value@mode, subscript@value@rank),\n logical0 = {\n Fortran(\":\", Variable(\"integer\", NA))\n },\n logical1 = {\n i <- scope@get_unique_var(\"integer\")\n f <- glue(\"pack([({i}, {i}=1, size({subscript}))], {subscript})\")\n return(Fortran(f, Variable(\"int\", NA)))\n },\n integer0 = {\n if (drop)\n subscript\n else\n Fortran(glue(\"{subscript}:{subscript}\"), Variable(\"int\", 1))\n },\n integer1 = {\n subscript\n },\n stop(\n \"all args to x[...] must be logical or integer of rank 0 or 1\",\n deparse1(as.call(c(quote(`[`, args ))))\n )\n )\n })\n dims <- drop_nulls(lapply(idxs, \\(idx) idx@value@dims[[1]]))\n outval <- Variable(var@value@mode, dims)\n Fortran(glue(\"{var}({str_flatten_commas(idxs)})\"), outval)\n}", "predict_code_clean": "r2f_handlers[[\"[\"]] <- function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n array_expr <- r2f(args[[1]], scope, ...)\n indices <- lapply(args[-1], function(idx) {\n if (is_missing(idx)) {\n return(Fortran(\":\"))\n }\n r2f(idx, scope, ...)\n })\n index_str <- str_flatten_commas(indices)\n fortran_code <- glue(\"{array_expr}({index_str})\")\n original_dims <- array_expr@value@dims\n new_dims <- if (length(indices) == 1 && array_expr@value@rank > 1) {\n list(original_dims[[1]] * original_dims[[2]])\n } else {\n original_dims[-seq_along(indices)]\n }\n Fortran(fortran_code, Variable(array_expr@value@mode, new_dims))\n}"}}
{"repo_name": "quickr", "file_name": "/quickr/R/sizes.R", "inference_info": {"prefix_code": "\n\n\ncheck_type_call <- function(cl) {\n if (length(cl) > 2)\n stop(\"only one variable can be declared per type() call\")\n args <- as.list(cl)[-1]\n if (length(names(args)) != 1)\n stop(\"name must be provided as: type(<name> = <mode>(<<dims>>)\")\n if (!is.call(args[[1]]) && as.character(args[[1]]) %in% .atomic_type_names)\n stop(\"only atomic modes are supported\")\n}\n\n\ntype_call_to_var <- function(cl) {\n check_type_call(cl)\n Variable(\n name = names(cl)[-1],\n mode = as.character(cl[[2L]][[1L]]),\n dims = unname(as.list(cl[[2]])[-1])\n )\n}\n\nvar_to_type_call <- function(var) {\n arg <- as.call(c(as.symbol(var@mode), var@dims))\n arg <- setNames(list(arg), var@name)\n as.call(c(quote(type), arg))\n}\n\n\nget_flattened_args <- function(cl) {\n # flatten exprs from `{` in usage like declare({ ... })`\n args <- as.list(cl)[-1]\n args <- lapply(args, function(e) {\n if (is_missing(e))\n NULL\n else if (is_call(e, quote(`{`)))\n get_flattened_args(e)\n else\n list(e)\n })\n unlist(args, recursive = FALSE)\n}\n\nself_evaluate <- function(...) sys.call()\n\nsubstitute_declared_sizes <- function(e) {\n stopifnot(is_call(e, quote(`{`)))\n\n aliases <- new.env(parent = emptyenv())\n eval_env <- new.env(parent = emptyenv())\n for(name in all.names(e, functions = TRUE, unique = TRUE))\n assign(name, self_evaluate, eval_env)\n eval_env <- new.env(parent = eval_env)\n for(name in all.names(e, functions = FALSE, unique = TRUE))\n assign(name, as.symbol(name), eval_env)\n\n eval_env$`{` <- function(...) {\n as.call(c(list(quote(`{`)), list(...)))\n }\n\n eval_env$declare <- function(...) {\n args <- get_flattened_args(sys.call())\n args <- lapply(args, function(e) {\n if (is_type_call(e)) {\n var <- type_call_to_var(e)\n var@dims <- imap(var@dims, ", "suffix_code": ")\n e <- var_to_type_call(var)\n }\n e\n })\n\n as.call(c(quote(declare), args))\n }\n\n e <- eval(e, eval_env)\n\n # Now the 'aliases' env is populated; go through and substitute\n # size aliases with the actual size name.\n eval_env$declare <- function(...) {\n as.call(lapply(sys.call(), function(e) {\n if (is_type_call(e))\n e <- substitute_(e, aliases)\n e\n }))\n }\n\n eval(e, eval_env)\n\n}\n\n\nr2size <- function(r, scope) {\n typeof(r) |> switch(\n integer = r,\n double = {\n if (is_wholenumber(r))\n as.integer(r)\n else\n stop(\"size must be an integer, found: \", r)\n },\n symbol = {\n if (is_size_name(r))\n return(r)\n var <- get(r, scope)\n if (var@mode != \"integer\" || !passes_as_scalar(var))\n warning(\"size is not an integer:\", as.character(r))\n if (var@is_arg && !var@modified)\n return(r)\n # TODO: add specific unit tests here\n if (identical(var@r, r))\n return(r)\n # make a best effort to use the r expression last assigned to the\n # symbol, or fail gracefully and return NA.\n # closure-locals with unspecified shape are declared allocatable\n # input and/or output args with unspecified shape signal an error.\n r2size(var@r, scope)\n },\n language = {\n as.character(r[[1]]) |> switch(\n `+` = , `-` = , `/` = , `*` = , `^` = , `%/%` = , `%%` = {\n args <- as.list(r)[-1]\n args <- lapply(args, r2size, scope)\n if (anyNA(rapply(args, as.list)))\n return(NA_integer_)\n cl <- as.call(c(r[[1]], args))\n if (all(map_lgl(args, is.atomic)))\n cl <- eval(cl, baseenv())\n cl\n },\n length = {\n var <- get(r[[2L]], scope)\n if (var@rank == 1)\n return(var@dims[[1L]])\n len <- reduce(var@dims, \\(d1, d2) call(\"*\", d1, d2))\n r2size(len, scope)\n },\n `[` = {\n # [ only works when paired with dim()\n if (!is_call(r[[2L]], quote(dim)))\n return(NA_integer_)\n var <- get(r[[2L]][[2L]], scope)\n axis <- r[[3]]\n if (!is_wholenumber(axis))\n return(NA_integer_)\n if (axis > var@rank)\n stop(\"insufficient rank of variable in \", deparse1(r))\n var@dims[[axis]]\n },\n # dim = {\n #\n # },\n nrow = {\n var <- get(r[[2L]], scope)\n var@dims[[1]]\n },\n ncol = {\n var <- get(r[[2L]], scope)\n var@dims[[2]]\n },\n NA_integer_)\n },\n NA_integer_\n )\n}\n\nr2dims <- function(r, scope) {\n if (is.call(r)) {\n as.character(r[[1]]) |> switch(\n dim = {\n var <- get(r[[2L]], scope)\n return(var@dims)\n },\n c = {\n args <- lapply(r[-1], r2dims, scope)\n dims <- unlist(args, recursive = FALSE)\n return(as.list(dims))\n },\n r <- list(r))\n }\n lapply(r, r2size, scope)\n}\n\nget_size_name <- function(var, axis = NULL, name = var@name, rank = var@rank) {\n stopifnot(is.null(axis) || is_wholenumber(axis) && axis > 0)\n if (is.null(axis) || rank == 1 && axis == 1)\n sprintf(\"%s__len_\", name)\n else {\n if (axis > rank) stop(\"axis must not be > rank\")\n sprintf(\"%s__dim_%i_\", name, axis)\n }\n}\n\n\n\n# TODO: allow syntax like:\n# declare(type(a, b, c = integer(1)))\n# or:\n# declare(type(a = , b = , c = integer(1)))\n", "middle_code": "function(size, axis) {\n size_name <- as.symbol(get_size_name(var, axis))\n if (is.symbol(size) && !exists(size, aliases)) {\n assign(as.character(size), size_name, aliases)\n size <- size_name\n } else if (is_scalar_na(size)) {\n size <- size_name\n } else if (is_wholenumber(size)) {\n size <- as.integer(size)\n }\n size\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/quickr/R/r2f.R", "\n\n\n# Take parsed R code (anything returnable by base::str2lang()) and returns\n# a Fortran object, which is a string of Fortran code and some attributes\n# describing the value.\nlang2fortran <- r2f <- function(e, scope = NULL, ..., calls = character(), hoist = NULL) {\n ## 'hoist()' is a function that individual handlers can call to pre-emit some\n ## Fortran code. E.g., to setup a temporary variable if the generated Fortran\n ## code doesn't neatly translate into a single expression.\n hoisted <- character()\n if (is.null(hoist)) {\n delayedAssign(\"hoist_connection\", textConnection(\"hoisted\", \"w\", TRUE))\n hoist <- function(...) {\n writeLines(as.character(unlist(c(character(), ...))),\n hoist_connection)\n }\n # if performance with textConnection() becomes an issue, maybe switch to an\n # anonymous file(), though, each hoisting context is typically shortlived and\n # usually 0 lines are hoisted per context, and if they are hoisted, a small number.\n }\n\n fortran <- switch(typeof(e),\n language = {\n # a call\n handler <- get_r2f_handler(callable <- e[[1L]])\n\n match.fun <- attr(handler, \"match.fun\", TRUE)\n if (is.null(match.fun)) {\n match.fun <- get0(callable, parent.env(globalenv()),\n mode = \"function\")\n # this is a best effort to, eg. resolve `seq.default` from `seq`.\n # This should likely be moved into attaching the `match.fun` attr\n # to handlers, for more involved resolution (e.g., with getS3Method())\n if (\"UseMethod\" %in% all.names(body(match.fun)))\n match.fun <- get0(paste0(callable, \".default\"),\n parent.env(globalenv()),\n mode = \"function\",\n ifnotfound = match.fun)\n }\n if (typeof(match.fun) == \"closure\") {\n e <- match.call(match.fun, e)\n }\n\n if (isTRUE(getOption(\"quickr.r2f.debug\"))) {\n\n try(handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)) -> res\n if (inherits(res, \"try-error\")) {\n debugonce(handler)\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n }\n\n res\n\n } else {\n\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n\n }\n\n },\n\n integer = ,\n double = ,\n complex = ,\n logical = atomic2Fortran(e),\n\n symbol = {\n s <- as.character(e)\n # logicals that come in from R are passed as integer types,\n # so for all fortran ops we cast to logical with /=0\n if (\n !is.null(scope[[e]] -> val) &&\n val@mode == \"logical\" &&\n val@is_external\n ) {\n s <- paste0(\"(\", s, \"/=0)\")\n }\n Fortran(s, value = scope[[e]])\n },\n\n ## handling 'object' and 'closure' here are both bad ideas,\n ## TODO: delete both\n # \"object\" = {\n # if (inherits(e, Variable))\n # e <- Fortran(character(), e)\n # stopifnot(inherits(e, Fortran))\n # e\n # },\n\n closure = {\n if (is.null(name <- attr(e, \"name\", TRUE))) {\n name <- if (is.symbol(name <- substitute(e)))\n as.character(name)\n else\n \"anonymous_function\"\n }\n\n stopifnot(is.null(scope))\n new_fortran_subroutine(name, e)\n },\n\n ## all the other typeof() possible values\n # \"character\",\n # \"raw\" ,\n # \"list\",\n # \"NULL\",\n # \"function\",\n # \"special\",\n # \"builtin\",\n # \"environment\",\n # \"S4\",\n # \"pairlist\",\n # \"promise\",\n # \"char\",\n # \"...\",\n # \"any\",\n # \"expression\",\n # \"externalptr\",\n # \"bytecode\",\n # \"weakref\"\n # default\n stop(\"Unsupported object type encountered: \", typeof(e))\n )\n\n if (length(hoisted)) {\n combined <- str_flatten_lines(c(hoisted, fortran))\n attributes(combined) <- attributes(fortran)\n fortran <- combined\n }\n\n attr(fortran, \"r\") <- e\n fortran\n}\n\n\natomic2Fortran <- function(x) {\n stopifnot(is_scalar_atomic(x))\n s <- switch(typeof(x),\n double =,\n integer = num2fortran(x),\n logical = if (x) \".true.\" else \".false.\",\n complex = sprintf(\"(%s, %s)\", num2fortran(Re(x)), num2fortran(Im(x))))\n Fortran(s, Variable(typeof(x)))\n}\n\nnum2fortran <- function(x) {\n stopifnot(typeof(x) %in% c(\"integer\", \"double\"))\n digits <- 7L\n nsmall <- switch(typeof(x), integer = 0L, double = 1L)\n repeat {\n s <- format.default(x, digits = digits, nsmall = nsmall, scientific = 1L)\n if (x == eval(str2lang(s))) # eval() needed for negative and complex numbers\n break\n add(digits) <- 1L\n if (digits > 22L)\n stop(\"number formatting error: \", x, \" formatted as : \", s)\n }\n paste0(s, switch(typeof(x), double = \"_c_double\", integer = \"_c_int\"))\n}\n\n\nr2f_handlers := new.env(parent = emptyenv())\n\nget_r2f_handler <- function(name) {\n stopifnot(\"All functions called must be named as symbols\" = is.symbol(name))\n get0(name, r2f_handlers) %||% stop(\"Unsupported function: \", name, call. = FALSE)\n}\n\nr2f_default_handler <- function(args, scope = NULL, ..., calls) {\n # stopifnot(is.call(e), is.symbol(e[[1L]]))\n\n x <- lapply(args, r2f, scope = scope, calls = calls, ...)\n s <- sprintf(\"%s(%s)\", last(calls), str_flatten_commas(x[-1]))\n Fortran(s)\n}\n\n## ??? export as S7::convert() methods?\nregister_r2f_handler <- function(name, fun) {\n stopifnot(\n is_string(name),\n identical(formals(fun), alist(x = , scope = NULL))\n )\n\n r2f_handlers[[name]] <- fun\n}\n\n.r2f_handler_not_implemented_yet <- function(e, scope, ...) {\n stop(gettextf(\"'%s' is not implemented yet\", as.character(e[[1L]])),\n call. = FALSE)\n}\n\nr2f_handlers[[\"declare\"]] <- function(args, scope, ...) {\n\n for (a in args) {\n if (is_missing(a)) {\n next\n }\n if (is_type_call(a)) {\n var <- type_call_to_var(a)\n var@is_arg <- var@name %in% names(formals(scope@closure))\n scope[[var@name]] <- var\n } else if (is_call(a, quote(`{`))) {\n Recall(as.list(a)[-1], scope)\n }\n }\n\n Fortran(\"\")\n}\n\n\nr2f_handlers[[\"Fortran\"]] <- function(args, scope = NULL, ...) {\n if (!is_string(args[[1]]))\n stop(\"Fortran() must be called with a string\")\n Fortran(args[[1]])\n # enable passing through literal fortran code\n # used like:\n # Fortran(\"nearest(x, 1)\", double(length(x)))\n # Fortran(\"nearest(x, 1)\", x)\n # Fortran(\"x = nearest(x, 1)\")\n}\n\nr2f_handlers[[\"(\"]] <- function(args, scope, ...) {\n r2f(args[[1L]], scope, ...)\n}\n\nr2f_handlers[[\"{\"]] <- function(args, scope, ..., hoist = NULL) {\n # every top level R-expr / fortran statement gets its own hoist target.\n x <- lapply(args, r2f, scope, ...)\n code <- str_flatten_lines(x)\n\n # browser()\n value <- (if (length(args)) last(x)@value) %||% Variable()\n Fortran(code, value)\n}\n\n\n\n# ---- reduction intrinsics ----\n\n\ncreate_mask_hoist <- function() {\n .hoisted_mask <- NULL\n\n try_set <- function(mask) {\n stopifnot(inherits(mask, Fortran), mask@value@mode == \"logical\")\n # each hoist can only accept one mask.\n if (is.null(.hoisted_mask)) {\n .hoisted_mask <<- mask\n return(TRUE)\n }\n # if the mask is identical, we accept it.\n if (identical(.hoisted_mask, mask)) {\n return(TRUE)\n }\n # can't hoist this mask.\n FALSE\n }\n\n get_hoisted <- function() .hoisted_mask\n\n environment()\n}\n\n\nr2f_handlers[[\"max\"]] <-\nr2f_handlers[[\"min\"]] <-\nr2f_handlers[[\"sum\"]] <-\nr2f_handlers[[\"prod\"]] <- function(args, scope, ...) {\n intrinsic <- switch(last(list(...)$calls),\n max = \"maxval\",\n min = \"minval\",\n sum = \"sum\",\n prod = \"product\")\n\n reduce_arg <- function(arg) {\n mask_hoist <- create_mask_hoist()\n x <- r2f(arg, scope, ..., hoist_mask = mask_hoist$try_set)\n if(x@value@rank == 0)\n return(x)\n hoisted_mask <- mask_hoist$get_hoisted()\n s <- glue(\n if (is.null(hoisted_mask))\n \"{intrinsic}({x})\"\n else\n \"{intrinsic}({x}, mask = {hoisted_mask})\"\n )\n Fortran(s, Variable(x@value@mode))\n }\n\n if (length(args) == 1) {\n reduce_arg(args[[1]])\n } else {\n args <- lapply(args, reduce_arg)\n mode <- reduce_promoted_mode(args)\n s <- switch(last(list(...)$calls),\n max = glue(\"max({str_flatten_commas(args)})\"),\n min = glue(\"min({str_flatten_commas(args)})\"),\n sum = glue(\"({str_flatten(args, ' + ')})\"),\n prod = glue(\"({str_flatten(args, ' * ')})\")\n )\n Fortran(s, Variable(mode))\n }\n}\n\n\nr2f_handlers[[\"which.max\"]] <-\nr2f_handlers[[\"which.min\"]] <-\nfunction(args, scope = NULL, ...) {\n stopifnot(length(args) == 1)\n x <- r2f(args[[1L]], scope, ...)\n stopifnot(\"Values passed to which.max()/which.min() must be 1d arrays\" = x@value@rank == 1)\n valout <- Variable(mode = \"integer\") # integer scalar\n\n if (x@value@mode == \"logical\") {\n val <- switch(last(list(...)$calls),\n which.max = \".true.\",\n which.min = \".false.\")\n f <- glue(\"findloc({x}, {val}, 1)\")\n } else {\n intrinsic <- switch(last(list(...)$calls),\n which.max = \"maxloc\",\n which.min = \"minloc\")\n f <- glue(\"{intrinsic}({x}, 1)\")\n }\n\n Fortran(f, valout)\n}\n\n\nr2f_handlers[[\"[\"]] <- function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n\n # only a subset of R's x[...] features can be translated here. `...` can only be:\n # - a single logical mask, of the same rank as `x`. returns a rank 1 vector.\n # - a number of arguments matching the rank of `x`, with each being\n # an integer of rank 0 or 1. In this case, a rank 1 logical becomes\n # converted to an integer with\n\n var <- args[[1]]\n var <- r2f(var, scope, ...)\n\n idxs <- whole_doubles_to_ints(args[-1])\n idxs <- imap(idxs, function(idx, i) {\n if (is_missing(idx))\n Fortran(\":\", Variable(\"integer\", var@value@dims[[i]]))\n else\n r2f(idx, scope, ...)\n })\n\n if (length(idxs) == 1 &&\n idxs[[1]]@value@mode == \"logical\" &&\n idxs[[1]]@value@rank == var@value@rank) {\n mask <- idxs[[1]]\n if (hoist_mask(mask))\n return(var)\n return(Fortran(glue(\"pack({var}, {mask})\"), Variable(var@value@mode, dims = NA)))\n }\n\n if (length(idxs) != var@value@rank)\n stop(\"number of args to x[...] must match the rank of x, received:\",\n deparse1(as.call(c(quote(`[`,args )))))\n\n drop <- args$drop %||% TRUE\n\n idxs <- lapply(idxs, function(subscript) {\n # if (!idx@value@rank %in% 0:1)\n # stop(\"all args to x[...] must have rank 0 or 1\",\n # deparse1(as.call(c(quote(`[`,args )))))\n switch(\n paste0(subscript@value@mode, subscript@value@rank),\n logical0 = {\n Fortran(\":\", Variable(\"integer\", NA))\n },\n logical1 = {\n # we convert to a temp integer vector, doing the equivalent of R's which()\n i <- scope@get_unique_var(\"integer\")\n f <- glue(\"pack([({i}, {i}=1, size({subscript}))], {subscript})\")\n return(Fortran(f, Variable(\"int\", NA)))\n },\n integer0 = {\n if (drop)\n subscript\n else\n Fortran(glue(\"{subscript}:{subscript}\"), Variable(\"int\", 1))\n },\n integer1 = {\n subscript\n },\n # double0 = { },\n # double1 = { },\n stop(\n \"all args to x[...] must be logical or integer of rank 0 or 1\",\n deparse1(as.call(c(quote(`[`, args ))))\n )\n )\n })\n\n dims <- drop_nulls(lapply(idxs, \\(idx) idx@value@dims[[1]]))\n outval <- Variable(var@value@mode, dims)\n Fortran(glue(\"{var}({str_flatten_commas(idxs)})\"), outval)\n\n}\n\n\nr2f_handlers[[\":\"]] <- function(args, scope, ...) {\n # depending on context, this translation can vary.\n\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n args <- whole_doubles_to_ints(args)\n .[start, end] <- lapply(args, r2f, scope, ...)\n step <- glue(\"sign(1, {end}-{start})\")\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{start}:{end}:{step}\"),\n \"for\" = glue(\"{start}, {end}, {step}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {start}, {end}, {step}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\nr2f_handlers[[\"seq\"]] <- function(args, scope, ...) {\n args <- whole_doubles_to_ints(args) # only casts if trunc(dbl) == dbl\n if (!is.null(args$length.out) || !is.null(args$along.with)) {\n stop(\"seq(length.out=, along.with=) not implemented yet\")\n }\n\n\n .[from, to, by] <- lapply(args, r2f, scope, ...)[c(\"from\", \"to\", \"by\")]\n by <- by %||% Fortran(glue(\"sign(1, {to}-{from})\"), Variable(\"integer\"))\n\n # Fortran only supports integer sequences in do and implicit do contexts.\n # to make a double sequence, needs to be in via an implied map() call, like\n # seq(1, 10, .1) -> [(x * 0.1, x = 10, 50)]\n #\n # e.g., i <- scope@get_unique_var(\"integer\")\n # glue(\"[({i} * by, {i} = int(from/by), int(to/by))]\")\n if (from@value@mode != \"integer\" ||\n to@value@mode != \"integer\" ||\n by@value@mode != \"integer\")\n stop(\"non-integer seq()'s not implemented yet.\")\n\n # depending on context, this translation can vary.\n #\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{from}:{to}:{by}\"),\n \"for\" = glue(\"{from}, {to}, {by}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {from}, {to}, {by}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\n\n\nr2f_handlers[[\"ifelse\"]] <- function(args, scope, ...) {\n .[mask, tsource, fsource] <- lapply(args, r2f, scope, ...)\n # (tsource, fsource, mask)\n mode <- tsource@value@mode\n dims <- conform(mask@value, tsource@value, fsource@value)@dims\n Fortran(glue(\"merge({tsource}, {fsource}, {mask})\"),\n Variable(mode, dims))\n}\n\n\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- pure elemental unary math intrinsics ----\n\n## real and complex intrinsics\nr2f_handlers[[\"sin\"]] <-\nr2f_handlers[[\"cos\"]] <-\nr2f_handlers[[\"tan\"]] <-\nr2f_handlers[[\"asin\"]] <-\nr2f_handlers[[\"acos\"]] <-\nr2f_handlers[[\"atan\"]] <-\nr2f_handlers[[\"sqrt\"]] <-\nr2f_handlers[[\"exp\"]] <-\nr2f_handlers[[\"log\"]] <-\nr2f_handlers[[\"floor\"]] <-\nr2f_handlers[[\"ceiling\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n intrinsic <- last(list(...)$calls)\n Fortran(glue(\"{intrinsic}({arg})\"), arg@value)\n}\n\nr2f_handlers[[\"log10\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n f <- if(arg@value@mode == \"complex\") {\n glue(\"(log({arg}) / log(10.0_c_double))\")\n } else {\n glue(\"log10({arg})\")\n }\n Fortran(f, arg@value)\n}\n\n## accepts real, integer, or complex\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n if(arg@value@mode == \"complex\")\n arg@value@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- complex elemental unary intrinsics ----\n\nr2f_handlers[[\"Re\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"real({arg})\"), val)\n}\n\nr2f_handlers[[\"Im\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"aimag({arg})\"), val)\n}\n\n# Modulus (magnitude)\nr2f_handlers[[\"Mod\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), val)\n}\n\n# Argument (phase angle, radians)\nr2f_handlers[[\"Arg\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"atan2(aimag({arg}), real({arg}))\"), val)\n}\n\n# conjg() returns a complex value; R uses Conj()\nr2f_handlers[[\"Conj\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"complex\"\n Fortran(glue(\"conjg({arg})\"), val)\n}\n\n\n\n# ---- elemental binary infix operators ----\n\nr2f_handlers[[\"+\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} + {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"-\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} - {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"*\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} * {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"/\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} / {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"^\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} ** {right})\"), conform(left@value, right@value))\n}\n\n\nr2f_handlers[[\">=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} >= {right})\"), var)\n}\nr2f_handlers[[\">\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} > {right})\"), var)\n}\nr2f_handlers[[\"<\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} < {right})\"), var)\n}\nr2f_handlers[[\"<=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} <= {right})\"), var)\n}\nr2f_handlers[[\"==\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} == {right})\"), var)\n}\nr2f_handlers[[\"!=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} /= {right})\"), var)\n}\n\n\n\n# ---- remainder (%%) and integer division (%/%) ----\n#\n# R semantics:\n# x %% y == r where r has the sign of y (divisor)\n# x %/% y == q where q = floor(x / y)\n# and x == r + y * q (within rounding error)\n#\n# Fortran intrinsics:\n# - MODULO(a,p) : remainder with sign(p)\n# - FLOOR(x) : greatest integer ≤ x (real)\n# - AINT(x) : truncation toward 0 (real)\n\nr2f_handlers[[\"%%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n # MODULO gives result with sign(right) – matches R %% behaviour\n Fortran(glue(\"modulo({left}, {right})\"), out_val)\n}\n\nr2f_handlers[[\"%/%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n\n expr <- switch(\n out_val@mode,\n integer = glue(\"int(floor(real({left}) / real({right})))\"),\n double = glue(\"floor({left} / {right})\"),\n stop(\"%/% only implemented for numeric types\")\n )\n\n Fortran(expr, out_val)\n}\n\n\n\n# TODO: the scalar || probably need some more type checking.\n# TODO: gfortran supports implicit casting that of logical to integer when\n# assigning a logical to a variable declared integer, converting `.true.` to `1`,\n# but this is not a standard language feature, and Intel's `ifort` uses `-1` for `.true`.\n# We should explicitly use\n# `merge(1_c_int, 0_c_int, <lgl>)` to cast logical to int.\nr2f_handlers[[\"&\"]] <-\nr2f_handlers[[\"&&\"]] <-\nr2f_handlers[[\"|\"]] <-\nr2f_handlers[[\"||\"]] <-\nfunction(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n args <- lapply(args, function(a) {\n if (a@value@mode != \"logical\") {\n stop(\"must be logical\")\n }\n a\n })\n .[left, right] <- args\n\n operator <- switch(last(list(...)$calls),\n `&` = , `&&` = \".and.\",\n `|` = , `||` = \".or.\")\n\n s <- glue(\"{left} {operator} {right}\")\n val <- conform(left@value, right@value)\n val@mode <- \"logical\"\n Fortran(s, val)\n}\n\n\n\n\n# --- constructors ----\n\n\nr2f_handlers[[\"c\"]] <- function(args, scope = NULL, ...) {\n ff <- lapply(args, r2f, scope, ...)\n s <- glue(\"[ {str_flatten_commas(ff)} ]\")\n lens <- lapply(ff[order(map_int(ff, \\(f) f@value@rank))], function(e) {\n rank <- e@value@rank\n if (rank == 0)\n 1L\n else if (rank == 1)\n e@value@dims[[1]]\n else\n stop(\"all args passed to c() must be scalars or 1-d arrays\")\n })\n mode <- reduce_promoted_mode(ff)\n len <- Reduce(\\(l1, l2) {\n if (is_scalar_na(l1) || is_scalar_na(l2)) {\n NA\n } else if (is_wholenumber(l1) && is_wholenumber(l2)) {\n l1 + l2\n } else {\n call(\"+\", l1, l2)\n }\n }, lens)\n Fortran(s, Variable(mode, list(len)))\n}\n\n\nr2f_handlers[[\"cbind\"]] <- function(e, scope) {\n .NotYetImplemented()\n ee <- lapply(e[-1], r2f, scope)\n ncols <- lapply(ee, function(f) {\n if (f@value@rank %in% c(0, 1))\n 1\n else if (f@value@rank == 2)\n f@value@dims[[2]]\n })\n ncols <- Reduce(\\(a, b) call(\"+\", a, b), ncols)\n ncols <- eval(ncols, scope@sizes)\n}\n\n\n\nr2f_handlers[[\"<-\"]] <- function(args, scope, ...) {\n target <- args[[1]]\n if (is.call(target)) {\n # given a call like `foo(x) <- y`, dispatch to `foo<-`\n target_callable <- target[[1]]\n stopifnot(is.symbol(target_callable))\n name <- as.symbol(paste0(as.character(target_callable), \"<-\"))\n handler <- get_r2f_handler(name)\n return(handler(args, scope, ...)) # new hoist target\n }\n\n # It sure seems like it's be nice if the Fortran() constructor\n # took mode and dims as args directly,\n # without needing to go through Variable...\n stopifnot(is.symbol(target))\n name <- as.character(target)\n\n value <- args[[2]]\n value <- r2f(value, scope, ...)\n\n # immutable / copy-on-modify usage of Variable()\n if (is.null(var <- get0(name, scope))) {\n # this is a binding to a new symbol\n var <- value@value\n var@name <- name\n scope[[name]] <- var\n\n } else {\n # The var already exists, this assignment is a modification / reassignment\n check_assignment_compatible(var, value@value)\n var@modified <- TRUE\n # could probably drop this @modified property, and instead track\n # if the var populated by declare is identical at the end (e.g., perhaps by\n # address, or by attaching a unique id to each var, or ???)\n assign(name, var, scope)\n }\n\n Fortran(glue(\"{name} = {value}\"))\n}\n\n\nr2f_handlers[[\"[<-\"]] <- function(args, scope = NULL, ...) {\n\n # TODO: handle logical subsetting here, which must become a where a construct like:\n # x[lgl] <- val\n # becomes\n # where (lgl)\n # x = val\n # end where\n # ! but if {va} references {x}, it will only see the subset x, not the full {x}\n # e.g.,\n # sum(x) is not the same as `where lgl \\n sum(x) \\n end where`\n # ditto for ifelse() ?\n # e <- as.list(e)\n\n stopifnot(is_call(target <- args[[1L]], \"[\"))\n target <- r2f(target, scope)\n\n value <- r2f(args[[2L]], scope)\n Fortran(glue(\"{target} = {value}\"))\n}\n\nreduce_promoted_mode <- function(...) {\n\n getmode <- function(d) {\n if (inherits(d, Fortran))\n d <- d@value\n if (inherits(d, Variable))\n return(d@mode)\n if (is.list(d) && length(d))\n lapply(d, getmode)\n }\n modes <- unique(unlist(getmode(list(...))))\n\n if (\"double\" %in% modes)\n \"double\"\n else if (\"integer\" %in% modes)\n \"integer\"\n else if (\"logical\" %in% modes)\n \"logical\"\n else\n NULL\n\n}\n\n\nr2f_handlers[[\"=\"]] <- r2f_handlers[[\"<-\"]]\n\nr2f_handlers[[\"logical\"]] <- function(args, scope, ...) {\n Fortran(\".false.\", Variable(mode = \"logical\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"integer\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"integer\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"double\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"double\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"numeric\"]] <- r2f_handlers[[\"double\"]]\n\nr2f_handlers[[\"character\"]] <- r2f_handlers[[\"raw\"]] <-\n .r2f_handler_not_implemented_yet\n\n\nr2f_handlers[[\"matrix\"]] <- function(args, scope = NULL, ...) {\n\n args$data %||% stop(\"matrix(data=) must be provided, cannot be NA\")\n out <- r2f(args$data, scope, ...)\n out@value@dims <- r2dims(list(args$nrow, args$ncol), scope)\n out\n\n # TODO: reshape() if !passes_as_scalar(out)\n}\n\n\n\nconform <- function(..., mode = NULL) {\n var <- NULL\n # technically, types are implicit promoted, but we'll let <- handle that.\n for (var in drop_nulls(list(...))) {\n if (passes_as_scalar(var)) {\n next\n } else {\n break\n }\n }\n if (is.null(var))\n NULL\n else\n Variable(mode %||% var@mode, var@dims)\n }\n\n\n\n# ---- printers ----\n\n\nr2f_handlers[[\"cat\"]] <- function(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n # can do a lot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"character\")\n label <- args[[1]]\n if (!endsWith(label, \"\\n\"))\n stop(\"cat(<strings>) must end with '\\n'\")\n label <- substring(label, 1, nchar(label)-1)\n\n Fortran(glue('call labelpr(\"{label}\", {nchar(label)})'))\n}\n\nr2f_handlers[[\"print\"]] <- function(args, scope = NULL, ...) {\n # args <- lapply(as.list(e)[-1], r2f, scope)\n # args <- as.list(e)[-1]\n # can do alot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"symbol\")\n name <- args[[1]]\n var <- get(name, envir = scope)\n name <- as.character(name)\n if (var@mode == \"logical\")\n name <- sprintf(\"(%s/=0)\", name)\n label <- \"\"\n # browser()\n if (passes_as_scalar(var)) {\n # } \"scalar\"\n # paste0(c(var@mode, scalar) collapse = \"_\"),\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr1\",\n double = \"dblepr1\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name})'))\n } else {\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr\",\n double = \"dblepr\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name}, size({name}))'))\n }\n}\n\n# r2f_handlers[[\"ifelse\"]] <- function(e, scope) {\n# # TODO:\n# # <- and [<- need to be aware of this construct for it to make sense.\n# .[test, yes, no] <- lapply(e[-1], r2f, scope)\n# Fortran(glue(\"where ({test}}\n# {indent(yes)}\n# elsewhere\n# {indent({no})\n# end where\"))\n# }\n\n\nr2f_handlers[[\"length\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x})\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"nrow\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 1)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"ncol\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 2)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"dim\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"shape({x})\"), Variable(\"integer\", x@value@rank))\n}\n\n\n\n\n# this is just `[` handler\nr2f_slice <- function(args, scope, ...) { }\n\n\n\n# ---- control flow ----\n\n\nr2f_handlers[[\"if\"]] <- function(args, scope, ..., hoist = NULL) {\n # cond uses the current hoist context.\n cond <- r2f(args[[1]], scope, ..., hoist = hoist)\n\n # true and false branchs gets their own hoist target.\n true <- r2f(args[[2]], scope, ..., hoist = NULL)\n\n if (length(args) == 2) {\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n end if\n \"))\n } else {\n false <- r2f(args[[3]], scope, ..., hoist = NULL)\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n else\n {indent(false)}\n end if\n \"))\n }\n}\n\n\n# TODO: return\n\n# ---- repeat ----\nr2f_handlers[[\"repeat\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n body <- r2f(args[[1]], scope, ...)\n Fortran(glue(\n \"do\n {indent(body)}\n end do\n \"))\n}\n\n# ---- break ----\nr2f_handlers[[\"break\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"exit\")\n}\n\n# ---- break ----\nr2f_handlers[[\"next\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"cycle\")\n}\n\n# ---- while ----\nr2f_handlers[[\"while\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 2L)\n cond <- r2f(args[[1]], scope, ...)\n body <- r2f(args[[2]], scope, ...) ## should we set a new hoist target here?\n Fortran(glue(\n \"do while ({cond})\n {indent(body)}\n end do\n \"))\n}\n\n## ---- for ----\nr2f_iterable <- function(e, scope, ...) {\n .NotYetImplemented()\n\n if (is.symbol(e)) {\n var <- get(e, scope)\n iterable <- r2f(...)\n }\n\n # list(var, iterable, body_prefix)\n}\n\n\n\n\nr2f_handlers[[\"for\"]] <- function(args, scope, ...) {\n .[var, iterable, body] <- args\n stopifnot(is.symbol(var))\n var <- as.character(var)\n scope[[var]] <- Variable(mode = \"integer\", name = var)\n\n iterable <- r2f_iterable_handlers[[as.character(iterable[[1]])]](iterable, scope)\n body <- r2f(body, scope, ...)\n\n Fortran(glue(\n \"do {var} = {iterable}\n {indent(body)}\n end do\n \"))\n}\n\nr2f_iterable_handlers := new.env()\n\nr2f_iterable_handlers[[\"seq_len\"]] <- function(e, scope, ...) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_len()\")\n x <- x[[1]]\n start <- 1L\n end <- r2f(x)\n glue(\"{start}, {end}\")\n}\n\nr2f_iterable_handlers[[\"seq\"]] <- function(e, scope) {\n\n ee <- match.call(seq.default, e)\n ee <- whole_doubles_to_ints(ee)\n\n start <- r2f(ee$from, scope)\n end <- r2f(ee$to, scope)\n step <- if (is.null(ee$by))\n glue(\"sign(1, {end}-{start})\")\n else\n r2f(ee$by, scope)\n\n str_flatten_commas(\n start, end, step\n )\n}\n\nr2f_iterable_handlers[[\":\"]] <- function(e, scope) {\n\n ee <- whole_doubles_to_ints(e)\n .[start, end] <- as.list(ee)[-1] |> lapply(r2f, scope)\n\n glue(\"{start}, {end}, sign(1, {end}-{start})\")\n}\n\n\n\nr2f_iterable_handlers[[\"seq_along\"]] <- function(e, scope) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_along()\")\n x <- x[[1]]\n start <- 1\n end <- sprintf(\"size(%s)\", r2f(x, scope))\n glue(\"{start}, {end}\")\n}\n\n\n# ---- helpers ----\n\ncheck_call <- function(e, nargs) {\n if (length(e) != (nargs+1L))\n stop(\"Too many args to: \", as.character(e[[1L]]))\n}\n"], ["/quickr/R/c-wrapper.R", "\nmake_c_bridge <- function(fsub, strict = TRUE, headers = TRUE) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n closure <- fsub@closure\n scope <- fsub@scope\n\n fsub_arg_names <- fsub@signature # arg names\n closure_arg_names <- names(formals(closure))\n\n c_body <- character()\n\n if (!all(closure_arg_names %in% fsub_arg_names))\n stop(\"Undeclared arguments: \", str_flatten_commas(setdiff(closure_arg_names, fsub_arg_names)))\n\n closure_arg_vars <- mget(closure_arg_names, scope)\n\n # first unpack all the input vars into named C variables (including sizes and pointer)\n append(c_body) <- lapply(closure_arg_vars, closure_arg_c_defs, strict = strict) |>\n rbind(\"\")\n\n ## TODO, might still need to define a length size for vars where rank>1, if in checks.\n\n # now do all size checks.\n append(c_body) <- lapply(closure_arg_vars, closure_arg_size_checks, scope = scope)\n\n # maybe define and allocate the output var\n n_protected <- 0L\n return_var <- get(closure_return_var_name(closure), scope)\n if (!return_var@name %in% closure_arg_names) {\n return_var@modified <- TRUE\n assign(return_var@name, return_var, scope)\n append(c_body) <- return_var_c_defs(return_var, fsub@scope)\n add(n_protected) <- 1L # allocated return var\n if (return_var@rank > 1)\n add(n_protected) <- 1L # allocated _dim_sexp\n }\n\n fsub_call_args <- fsub_arg_names |>\n lapply(\\(nm) paste0(nm, if (!is_size_name(nm)) \"__\")) |>\n unlist()\n\n if (length(fsub_call_args) > 3)\n fsub_call_args <- paste0(\"\\n \", fsub_call_args)\n\n append(c_body) <- c(\"\", glue(\"{fsub@name}({str_flatten_commas(fsub_call_args)});\"), \"\")\n if (n_protected > 0)\n append(c_body) <- glue(\"UNPROTECT({n_protected});\")\n append(c_body) <- glue(\"return {return_var@name};\")\n\n c_args <- paste(\"SEXP\", names(formals(closure)), collapse = \", \")\n c_body <- as_glue(str_flatten_lines(c_body))\n\n c_func_def <- glue(\"SEXP {fsub@name}_(SEXP _args) {c_block(c_body)}\")\n\n fsub_extern_decl <- fsub_extern_decl(fsub)\n\n c_headers <- glue::trim(r\"--(\n #define R_NO_REMAP\n #include <R.h>\n #include <Rinternals.h>\n\n\n )--\")\n\n as_glue(str_flatten_lines(c(\n if (headers) c_headers,\n fsub_extern_decl, \"\",\n c_func_def)\n ))\n}\n\n\nclosure_arg_c_defs <- function(var, strict = TRUE) {\n\n name <- var@name\n mode <- var@mode\n\n c_code <- character()\n\n name <- var@name\n SEXPTYPE <- sexptype(var@mode)\n protect <- glue(\"SETCAR(_args, {var@name});\")\n\n append(c_code) <- glue(\n \"// {name}\n _args = CDR(_args);\n SEXP {var@name} = CAR(_args);\")\n\n # first maybe duplicate or coerce the SEXP if needed.\n append(c_code) <- glue(\"if (TYPEOF({name}) != {SEXPTYPE}) {{\")\n append(c_code) <- indent(if (strict) {\n glue(r\"(\n Rf_error(\"typeof({name}) must be '{mode}', not '%s'\", R_typeToChar({name}));\n )\")\n } else {\n glue(\"{name} = Rf_coerceVector({name}, {SEXPTYPE});\n {protect}\")\n })\n\n\n if (var@modified) {\n dup <- glue('\n {name} = Rf_duplicate({name});\n {protect}\n ')\n\n if (strict) {\n append(c_code) <- c(\"}\", dup)\n } else {\n append(c_code) <- sprintf(\"} else %s\", dup)\n }\n\n } else {\n append(c_code) <- \"}\"\n }\n\n # define the variable that will be passed to the fsub\n append(c_code) <- glue(\n \"{fsub_arg_var_c_type(var)} {name}__ = {sexpdata(var@mode)}({name});\")\n\n\n if (var@rank == 1) {\n size_name <- get_size_name(var)\n append(c_code) <- glue(\"const R_xlen_t {size_name} = Rf_xlength({var@name});\")\n } else if (var@rank > 1) {\n append(c_code) <- glue(\n 'const int* const {var@name}__dim_ = ({{\n SEXP dim_ = Rf_getAttrib({var@name}, R_DimSymbol);\n if (Rf_length(dim_) != {var@rank}) Rf_error(\n \"{var@name} must be a {var@rank}D-array, but length(dim({var@name})) is %i\",\n (int) Rf_length(dim_));\n INTEGER(dim_);}});'\n )\n append(c_code) <- map_chr(seq_len(var@rank), \\(axis) {\n size_name <- get_size_name(var, axis)\n glue(\"const int {size_name} = {var@name}__dim_[{axis-1}];\")\n })\n } else {\n stop(\"bad rank\")\n }\n\n as_glue(str_flatten_lines(c_code))\n}\n\n\n\nclosure_arg_size_checks <- function(var, scope) {\n imap(var@dims, function(d, axis) {\n # axis is either:\n # - an integer\n # - a symbol of a size_name\n # - a call, consisting of only size_name symbols and basic arithmetic ops.\n size_name <- get_size_name(var, axis)\n\n if (is_scalar_integer(d)) {\n return(glue('\n if ({size_name} != {d})\n Rf_error(\"{friendly_size(var, axis)} must be {d}, not %0.f\",\n (double){size_name});'\n ))\n }\n\n if (is.symbol(d)) {\n if (as.character(d) == size_name) {\n # self-named size_name is expected to be passed along to subroutine\n return()\n } else {\n # it's a constraint for another size\n return(glue('\n if ({d} != {size_name})\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_name(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double){d});'\n ))\n }\n }\n\n if (is.call(d)) {\n size.c <- dims2c(list(d), scope)\n return(glue('{{\n const R_xlen_t expected = {size.c};\n if ({size_name} != expected)\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_expression(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double)expected);\n }}'\n ))\n }\n\n stop(\"bad dim\")\n })\n}\n\n\n\n\nreturn_var_c_defs <- function(var, scope) {\n # allocate the return var.\n name <- var@name\n c_dims <- dims2c(var@dims, scope)\n c_len <- c_dims2c_len(c_dims)\n len_name <- get_size_name(var)\n\n c_code <- c(\n glue(\"const R_xlen_t {len_name} = {c_len};\"),\n glue(switch(\n var@mode,\n double = \"\n SEXP {name} = PROTECT(Rf_allocVector(REALSXP, {len_name}));\n double* {name}__ = REAL({name});\",\n integer = \"\n SEXP {name} = PROTECT(Rf_allocVector(INTSXP, {len_name}));\n int* {name}__ = INTEGER({name});\",\n complex = \"\n SEXP {name} = PROTECT(Rf_allocVector(CPLXSXP, {len_name}));\n Rcomplex* {name}__ = COMPLEX({name});\",\n logical = \"\n SEXP {name} = PROTECT(Rf_allocVector(LGLSXP, {len_name}));\n int* {name}__ = LOGICAL({name});\"\n )))\n\n if (var@rank > 1) {\n append(c_code) <- c_block(\n glue(\"\n const SEXP _dim_sexp = PROTECT(Rf_allocVector(INTSXP, {var@rank}));\n int* const _dim = INTEGER(_dim_sexp);\"\n ),\n imap(c_dims, function(d, i) {\n glue(\"_dim[{i-1}] = {d};\")\n }),\n glue(\"Rf_dimgets({var@name}, _dim_sexp);\")\n )\n }\n\n str_flatten_lines(c_code)\n}\n\n\n\n\ndims2c_eval_base_env <- new.env()\n\n\ndims2c_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\ndims2c_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2c_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2c_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2c_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"((double)({e1}) / (double)({e2}))\")\n# dividing integers truncates towards 0\ndims2c_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} / (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} % (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1}**{e2})\")\n\n\ndims2c <- function(dims, scope) {\n if (!length(dims) || identical(dims, list(1L))) {\n return(list(NULL, \"1\"))\n }\n\n syms <- as.character(unique(unlist(lapply(dims, all.vars))))\n\n syms <- mget(syms, scope, ifnotfound = syms) |>\n lapply(function(var) {\n if (is_size_name(var)) {\n return(as.character(var))\n }\n # resolve a variable from scope (i.e., some other arg var)\n if (!inherits(var, Variable))\n stop(\"could not resolve size: \", var)\n glue(\"Rf_asInteger({var@name})\")\n # Should this be as double?\n # TODO: force this into a named c var, to avoid repeated calls\n })\n\n eval_env <- list2env(syms, parent = dims2c_eval_base_env)\n c_dims <- lapply(dims, function(d) {\n if (inherits(d, Variable))\n return(glue(\"Rf_asInteger({d@name})\"))\n eval(d, eval_env)\n })\n\n c_dims\n}\n\nc_dims2c_len <- function(c_dims) {\n if (length(c_dims) == 1)\n c_dims[[1L]]\n else\n paste0(\"(\", unlist(c_dims), \")\", collapse = \" * \" )\n # eval(Reduce(\\(a, b) { call(\"*\", as.symbol(a@name), as.symbol(b@name)) }, dims),\n # eval_env)\n}\n\n\n# --- utils ----\n\nc_block <- function(...) {\n as_glue(paste0(c(\"{\", indent(c(...)), \"}\"), collapse = \"\\n\"))\n}\n\n# is_var_size <- function(x) inherits(x, VariableSize)\n\npasses_as_scalar <- function(var) {\n var@rank == 0 || var@rank == 1 && identical(var@dims, list(1L))\n}\n\npasses_as_value <- function(var) {\n passes_as_scalar(var) && isFALSE(var@modified)\n}\n\nsexptype <- function(mode) {\n switch(mode,\n integer = \"INTSXP\",\n double = \"REALSXP\",\n complex = \"CPLXSXP\",\n logical = \"LGLSXP\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nsexpdata <- function(mode) {\n switch(mode,\n integer = \"INTEGER\",\n double = \"REAL\",\n complex = \"COMPLEX\",\n logical = \"LOGICAL\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nis_size_name <- function(name) {\n if (is.symbol(name)) {\n name <- as.character(name)\n } else if (!is_string(name)) {\n return(FALSE)\n }\n\n grepl(\"(_len_|_dim_[0-9]+_)$\", name)\n}\n\nfriendly_size <- function(var, axis = NULL) {\n if (is.null(axis) || var@rank == 1 && axis == 1)\n glue(\"length({var@name})\")\n else\n glue(\"dim({var@name})[{axis}]\")\n}\n\nas_friendly_size_name <- function(size_name) {\n size_name <- as.character(size_name)\n if (endsWith(size_name, \"__len_\"))\n sprintf(\"length(%s)\", sub(\"__len_$\", \"\", size_name))\n else\n sub(\"^(.*)__dim_([0-9]+)_$\", \"dim(\\\\1)[\\\\2]\", size_name)\n}\n\nas_friendly_size_expression <- function(d) {\n stopifnot(is.call(d))\n nms <- all.names(d, functions = FALSE, unique = TRUE)\n friendly_substitutions <- new.env(parent = emptyenv())\n for(name in nms)\n if (is_size_name(name))\n assign(name, str2lang(as_friendly_size_name(name)), friendly_substitutions)\n d <- substitute_(d, friendly_substitutions)\n d <- call(\"(\", d)\n deparse1(d)\n}\n\nclosure_return_var_name <- function(closure) {\n return_var_name <- last(body(closure))\n if (!is.symbol(return_var_name))\n stop(\"return value must be a symbol\")\n as.character(return_var_name)\n}\n\n\nfsub_arg_var_c_type <- function(var) {\n type <- switch(var@mode,\n double = \"double*\",\n integer = \"int*\",\n complex = \"Rcomplex*\",\n logical = \"int*\",\n )\n\n # the first const declares that the pointed to values can't be modified\n # (the array values are read only)\n # the second const declares that the pointer itself can't be modified\n # (the fsub can never move/reallocate the array, so this const is always present)\n paste0(c(if (!var@modified) \"const\", type, \"const\"),\n collapse = \" \")\n}\n\nfsub_extern_decl <- function(fsub) {\n fsub_arg_names <- fsub@signature # arg names\n scope <- fsub@scope\n\n fsub_c_sig <- map_chr(fsub_arg_names, function(name) {\n if (is_size_name(name)) {\n type <- if (endsWith(\"__len_\", name))\n \"R_xlen_t\" else \"R_len_t\"\n glue(\"const {type} {name}\")\n } else {\n var <- get(name, fsub@scope)\n glue(\"{fsub_arg_var_c_type(var)} {var@name}__\")\n }\n })\n if (length(fsub_c_sig) >= 3L)\n fsub_c_sig <- paste0(\"\\n \", fsub_c_sig)\n\n glue(\"extern void {fsub@name}({str_flatten_commas(fsub_c_sig)});\")\n}\n"], ["/quickr/R/manifest.R", "\n\n\n### local variables with unspecified size are 'allocatable'. If they are bound\n### to a named symbol, the manifest must mark it as allocatable.\n###\n### Generally, if an expression produces an array of unspecified size, even if\n### it's never bound, it's still 'allocatable'. For example, an inline fortran\n### `pack()` call likely still produces a corresponding `malloc()` in the\n### generated code, regardless of if the output of `pack()` is bound to\n### a symbol (in the case of pack specifically, the malloc is behind a\n### _gfortran_pack() call.\n###\n### We can potentially link/mask `_malloc` and `_free` with a custom one that\n### uses R_alloc(), which will automatically free after the .External() call\n### returns. We can also pass along -fstack-arrays to gfortran and flang-new\n### (llvm), and that will mostly get rid most of the malloc calls, instead\n### allocating arrays on the C stack (which will automatically free on\n### return/lngjmp), but that will run into issues with larger arrays (especially\n### on windows)\n###\n### local vars of undefined sizes are allocatable. These will typically be\n### allocated on the c stack if they are not too large, but may include a\n### malloc+free call if they are large. Those might leak if we lngjmp\n### away (e.g., due to an interrupt). This potential leak is a non-issue for\n### now, since interrupts aren't supported yet, so there is no risk of lngjmp.\n###\n### When we do add support for interruptable quick functions, this potential\n### leak could be guarded against by:\n###\n### a) linking malloc -> R_alloc() for the fortran compilation unit which\n### would make the memory automatically be released after .External()\n### return. Note that unlinke malloc(), R_alloc() is not thread safe, so we would need\n### additional work for a `do concurrent` context to be supported.\n###\n### b) forcing all arrays to be stack allocated with -fstack-arrays passed\n### to the gfortran/flang-new. This is not a great, since c stack limits are\n### typically \"small\" and enforced by the OS.\n\nr2f.scope <- function(scope) {\n\n vars <- as.list.environment(scope, all.names = TRUE)\n vars <- lapply(vars, function(var) {\n\n intent_in <- var@name %in% names(formals(scope@closure))\n intent_out <- var@name == closure_return_var_name(scope@closure) || intent_in && var@modified\n\n intent <-\n if (intent_in && intent_out) \"intent(in out)\"\n else if (intent_in) \"intent(in)\"\n else if (intent_out) \"intent(out)\"\n else NULL\n\n type <- switch(var@mode,\n double = \"real(c_double)\",\n integer = \"integer(c_int)\",\n complex = \"complex(c_double_complex)\",\n logical = if (intent_in || intent_out) \"integer(c_int)\" else \"logical\",\n raw = \"integer(c_int8_t)\",\n stop(\"unrecognized kind: \", format(var))\n )\n\n dims <- if (passes_as_scalar(var)) {\n NULL\n } else {\n dims2f(var@dims, scope) |> str_flatten_commas() |> sprintf(fmt = \"(%s)\")\n }\n\n allocatable <- if (!is.null(dims) && grepl(\":\", dims, fixed = TRUE))\n \"allocatable\"\n\n if (intent_in && intent_out && !is.null(allocatable))\n stop(\"all input and output vars must have a fully defined shape\")\n\n name <- var@name\n comment <- if (var@mode == \"logical\") \" ! logical\"\n\n glue('{str_flatten_commas(type, intent, allocatable)} :: {name}{dims}{comment}',\n .null = \"\")\n })\n\n # vars that will be visible in the C bridge, either as an input or output\n non_local_var_names <- unique(c(names(formals(scope@closure)),\n closure_return_var_name(scope@closure)))\n\n # collect all size_names; sort so non-locals are declared first.\n size_names <- unique(unlist(lapply(non_local_var_names, function(name) {\n var <- scope[[name]]\n lapply(var@dims, all.names, functions = FALSE, unique = TRUE)\n }))) |> setdiff(names(formals(scope@closure)))\n\n sizes <- lapply(size_names, function(name) {\n kind <- if (endsWith(name, \"_len_\")) \"c_ptrdiff_t\" else \"c_int\"\n glue(\"integer({kind}), intent(in), value :: {name}\")\n })\n\n manifest <- compact(list(\n sizes = sizes,\n args = vars[non_local_var_names],\n locals = vars[setdiff(names(vars), non_local_var_names)]\n ))\n\n manifest <- imap(manifest, \\(declarations, category)\n str_flatten_lines(paste(\"!\", category), declarations)) |>\n str_flatten(\"\\n\\n\")\n\n manifest <- str_flatten_lines(\"! manifest start\", manifest, \"! manifest end\")\n\n # symbols that must come in as args to the subroutine\n # # method=\"radix\" for locale-independent stable order.\n signature <- unique(c(non_local_var_names, sort(size_names, method = \"radix\")))\n attr(manifest, \"signature\") <- signature\n\n manifest\n}\n\n\n\n## fortran precedence order\n## ** (exp)\n## * /\n## + -\n##\n## R prededence order\n## ^\n## - +\n## %/% %%\n## * /\n\n## generally, we just deparse() to convert an axis size.\n## except for NA, which becomes \":\"\n\ndims2f_eval_base_env <- new.env(parent = emptyenv())\ndims2f_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\n\n# any call always evaluates to a string.\n# every argument will be either:\n# - NA -> translates to \":\"\n# - a symbol -> translates to deparsed string\n# - a call ->\n\ndims2f_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2f_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2f_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2f_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"real({e1}) / real({e2})\")\n# dividing integers truncates towards 0\ndims2f_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"int({e1}) / int({e2})\")\ndims2f_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"mod(int({e1}), int({e2}))\")\ndims2f_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1})**({e2})\")\n\n\ndims2f <- function(dims, scope) {\n syms <- unique(unlist(lapply(dims, \\(d) if (is.language(d)) all.vars(d))))\n vars <- as.list(syms)\n names(vars) <- syms\n eval_env <- list2env(vars, parent = dims2f_eval_base_env)\n dims <- map_chr(dims, function(d) {\n d <- eval(d, eval_env)\n if (is.symbol(d)) as.character(d)\n else if (is_wholenumber(d)) as.character(d)\n else if (is_scalar_na(d)) \":\"\n else if (is_string(d)) d\n else if (inherits(d, Variable)) {\n # a locally allocated var that is a return var\n if (!d@modified && d@is_arg)\n return(d@name)\n stop(\"unexpected axis size value\")\n }\n })\n if (!length(dims) || identical(dims, \"1\")) \"\"\n else str_flatten_commas(dims)\n}\n\n"], ["/quickr/R/classes.R", "#' @import S7\nNULL\n\nnew_setter <- function(coerce = NULL, coerce_null = FALSE, set_once = FALSE, env = parent.frame(2L)) {\n\n if (is.null(coerce) || isFALSE(coerce) && isFALSE(set_once))\n return()\n\n bind_name <- quote(name <- as.character(last(attr(self, \".setting_prop\", TRUE))))\n\n check_set_once <- if (set_once) {\n quote(if (!is.null(prop(self, name)))\n stop(name, \" can only be set once\"))\n }\n\n rebind_coerced_value <-\n if (is.null(coerce) || isFALSE(coerce)) {\n NULL\n } else if (isTRUE(coerce)) {\n quote(value <- convert(\n from = value,\n to = S7_class(self)@properties[[as.character(name)]]$class\n ))\n } else if (is.function(coerce) || is.symbol(coerce)) {\n bquote(value <- .(coerce)(value))\n } else if (is.language(coerce)) {\n bquote(value <- .(coerce))\n } else {\n stop(\"coerce must be TRUE, FALSE, NULL, a function, a symbol, or a call\")\n }\n\n if (!coerce_null && !is.null(rebind_coerced_value)) {\n rebind_coerced_value <- bquote(if (!is.null(value)) .(rebind_coerced_value))\n }\n\n set <- quote(`prop<-`(\n object = self,\n name = name,\n check = FALSE,\n value = value\n ))\n\n new_function(\n args = alist(self = , value = ),\n body = as.call(c(quote(`{`),\n bind_name,\n check_set_once,\n rebind_coerced_value,\n set)),\n env = env\n )\n}\n\n\nnew_scalar_validator <- function(allow_null = FALSE,\n allow_na = FALSE,\n additional_checks = NULL,\n env = parent.frame(2L)) {\n checks <- c(\n if (allow_null) quote(if (is.null(value)) return()),\n quote(if (length(value) != 1L) return(\"must be a scalar\")),\n if (!allow_na) quote(if (anyNA(value)) return(\"must not be NA\")),\n additional_checks\n )\n\n new_function(\n args = alist(value = ),\n body = as.call(c(quote(`{`), checks)),\n env = parent.frame(2L)\n )\n}\n\n\nprop_bool <- function(default, allow_null = FALSE, allow_na = FALSE, set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n new_property(\n class = if (allow_null) NULL | class_logical else class_logical,\n setter = new_setter(set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null,\n allow_na = allow_na),\n default = default\n )\n}\n\n\nprop_string <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = FALSE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(as.character)\n\n new_property(\n class = if (allow_null) NULL | class_character else class_character,\n default = default,\n validator = new_scalar_validator(allow_null = allow_null),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once)\n )\n}\n\n\nprop_wholenumber <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = TRUE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(\n if (is_wholenumber(value)) as.integer(value)\n else stop(\"@\", name, \" must be a whole number, but received: \", value)\n )\n\n new_property(\n class = if (allow_null) NULL | class_integer else class_integer,\n default = as.integer(default),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null)\n )\n}\n\n\nprop_enum <- function(values,\n nullable = FALSE,\n default = if (nullable) NULL else values[1],\n exact = FALSE,\n set_once = FALSE) {\n\n stopifnot(\n \"values must be a character vector of length >= 2 without any NA\" =\n is.character(values) && length(values) >= 2 && !anyNA(values)\n )\n\n coerce <- if (exact) NULL else {\n bquote(if (length(value) == 1L && !anyNA(i <- charmatch(value, .(values))))\n .(values)[i] else value)\n }\n\n display_values <- glue_collapse(single_quote(values), sep = \", \", last = \", or \")\n msg <- sprintf(\"must be either %s, not '\", display_values)\n validator <- new_scalar_validator(allow_null = nullable,\n additional_checks = bquote(\n if (!match(value, .(values), nomatch = 0L))\n return(paste0(.(msg), value, \"'.\"))\n ))\n\n new_property(\n class = if (nullable) NULL | class_character else class_character,\n setter = new_setter(coerce = coerce, coerce_null = !nullable, set_once = set_once),\n validator = validator,\n default = default\n )\n}\n\n\n.atomic_type_names <- c(\"integer\", \"logical\", \"double\",\n \"character\", \"raw\", \"complex\")\n\n\n# the print method for this should only print non-null values\nVariable := new_class(\n properties = list(\n\n mode = prop_enum(.atomic_type_names, nullable = TRUE, set_once = FALSE),\n\n dims = new_property(\n # NULL means scalar\n NULL | class_list,\n setter = function(self, value) {\n if (!length(value))\n return(self)\n\n value <- switch(typeof(value),\n logical = , integer = , double = as.list(value),\n language = , symbol = list(value), # implicit rank-1\n list = value,\n stop(\"@dims must be a list\")\n )\n\n value <- lapply(value, \\(axis) {\n if (is.language(axis)) {\n axis\n } else if (is_wholenumber(axis) || is_scalar_na(axis)) {\n as.integer(axis)\n } else {\n stop(sprintf(\n \"%s@dims must be a list of language or scalar integers, not %s\",\n self@name %||% '', axis\n ))\n }\n })\n\n self@dims <- value\n self\n } # dims$setter\n ), # dims = new_property()\n\n name = prop_string(\n allow_null = TRUE,\n coerce = quote(switch(typeof(value), symbol = as.character(value), value)),\n set_once = FALSE #TRUE\n ),\n\n rank = new_property(\n class_integer,\n getter = function(self) {\n length(self@dims)\n }),\n\n modified = prop_bool(default = FALSE),\n\n r = new_property(\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n # custom setter to workaround https://github.com/RConsortium/S7/issues/511\n attr(self, \"r\") <- value\n self\n }\n ),\n\n is_arg = prop_bool(default = FALSE),\n\n is_return = prop_bool(default = FALSE),\n\n # TRUE for closure args and return values, FALSE for all other vars.\n is_external = new_property(\n class_logical,\n getter = function(self)\n self@is_arg || self@is_return\n ),\n\n is_scalar = new_property(\n class_logical,\n getter = function(self) {\n self@rank == 0 || identical(self@dims, list(1L))\n }\n )\n\n )\n)\n\n# method(print, Variable) <- function(x, ...) {\n#\n# }\n\n\n\nFortran := new_class(\n class_character,\n\n properties = list(\n\n value = NULL | Variable,\n\n r = new_property(\n # custom setter only to workaround https://github.com/RConsortium/S7/issues/511\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n attr(self, \"r\") <- value\n self\n }\n )\n ),\n\n validator = function(self) {\n if (length(self) != 1L)\n \"must be a length 1 string\"\n }\n)\n\n\nFortranSubroutine := new_class(Fortran, properties = list(\n name = prop_string(),\n signature = class_character,\n closure = class_function,\n scope = NULL | class_environment,\n c_bridge = S7::new_property(\n NULL | class_character,\n getter = function(self) {\n make_c_bridge(self) %error% NULL\n })\n))\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\ntry_prop <- function(object, name) S7::prop(object, name) %error% NULL\n\nemit <- function(..., sep = \"\", end = \"\\n\") cat(..., end, sep = sep)\n\nmethod(format, Variable) <- function(x, ...) {\n capture.output(str(x))\n}\n\nmethod(as.character, Variable) <- function(x, ...)\n x@name %||% stop(\"Variable does not have a name\")\n\nmethod(print, Fortran) <- function(x, ...) {\n emit(trimws(x), end = \"\\n\\n\")\n for(prop_name in c(\"value\", \"r\", \"c_bridge\"))\n if (!is.null(prop_val <- try_prop(x, prop_name))) {\n emit(\"@\", prop_name, \": \", trimws(indent(format(prop_val))));\n }\n}\n"], ["/quickr/R/subroutine.R", "\n\nnew_fortran_subroutine <- function(name, closure, parent = emptyenv()) {\n\n\n check_all_var_names_valid(closure)\n\n # translate body, and populate scope with variables\n body <- body(closure)\n\n # defuse calls like `-1` and `1+1i`. Not really necessary, but simplifies downstream a little.\n body <- defuse_numeric_literals(body)\n\n # TODO: try harder here to use one of the input vars as the output var\n body <- ensure_last_expr_sym(body)\n\n # update closure with sym return value\n base::body(closure) <- body\n # body <- rlang::zap_srcref(body)\n\n scope <- new_scope(closure, parent)\n\n # inject symbols for var sizes in declare calls, so like:\n # declare(type(foo = integer(nr, NA)),\n # type(bar = integer(nr, 3)))\n # become:\n # declare(type(foo = integer(foo_dim_1_, foo_dim_2_)),\n # type(bar = integer(foo_dim_1_, 3L)))\n body <- substitute_declared_sizes(body)\n body <- r2f(drop_last(body), scope)\n\n # check all input vars were declared\n # TODO: this check might be too late, because r2f() might throw cryptic errors\n # when handling undeclared variables. Either throw better errors from r2f(), or\n # handle all declares first\n for(arg_name in names(formals(closure))) {\n if (is.null(var <- get0(arg_name, scope)))\n stop(\"arg not declared: \", arg_name)\n }\n\n # figure out the return variable.\n if (is.symbol(last_expr <- last(body(closure)))) {\n return_var <- get(last_expr, scope)\n return_var@is_return <- TRUE\n scope[[as.character(last_expr)]] <- return_var\n } else {\n # lots we can still do here, just not implemented yet.\n stop(\"last expression in the function must be a bare symbol\")\n }\n\n manifest <- r2f.scope(scope)\n fsub_arg_names <- attr(manifest, \"signature\", TRUE)\n\n used_iso_bindings <- unique(unlist(use.names = FALSE, list(\n lapply(scope, function(var) {\n list(\n switch(\n var@mode,\n double = \"c_double\",\n integer = \"c_int\",\n logical = if (var@name %in% fsub_arg_names)\n \"c_int\",\n complex = \"c_double_complex\",\n raw = \"c_int8_t\"\n ),\n lapply(var@dims, function(size) {\n syms <- all.vars(size)\n c(if (any(grepl(\"__len_$\", syms))) \"c_ptrdiff_t\",\n if (any(grepl(\"__dim_[0-9]+_$\", syms))) \"c_int\")\n })\n )\n }))))\n\n # check for literal kinds\n if (!\"c_int\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+_c_int\\\\b\", body))\n append(used_iso_bindings) <- \"c_int\"\n }\n if (!\"c_double\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+\\\\.[0-9]+_c_double\\\\b\", body))\n append(used_iso_bindings) <- \"c_double\"\n }\n used_iso_bindings <- sort(used_iso_bindings, method = \"radix\")\n\n subroutine <- glue(\"\n subroutine {name}({str_flatten_commas(fsub_arg_names)}) bind(c)\n use iso_c_binding, only: {str_flatten_commas(used_iso_bindings)}\n implicit none\n\n {indent(manifest)}\n\n {indent(body)}\n end subroutine\n \")\n\n subroutine <- insert_fortran_line_continuations(subroutine)\n\n FortranSubroutine(\n subroutine,\n name = name,\n signature = fsub_arg_names,\n scope = scope,\n closure = closure\n )\n}\n\ninsert_fortran_line_continuations <- function(code, preserve_attributes = TRUE) {\n attrs_in <- attributes(code)\n\n code <- as.character(code)\n lines <- str_split_lines(code)\n lines <- trimws(lines, \"right\")\n\n if (any(too_long <- nchar(lines) > 132)) {\n # remove leading indentation\n lines[too_long] <- trimws(lines[too_long], \"left\")\n\n # move trailing comment at the end\n lines[too_long] <- sub(\"^(.*)!(.*)$\", \"!\\\\2\\n\\\\1\", lines[too_long])\n lines <- str_split_lines(lines)\n\n # maximum 255 continuations are allowed\n for (i in 1:256) {\n if (!any(too_long <- nchar(lines) > 132))\n break\n lines[too_long] <- sub(\"^(.{1,130})\\\\s\", \"\\\\1 &\\n\", lines[too_long])\n lines <- str_split_lines(lines)\n }\n if (i > 255L)\n stop(\"Too long line encountered. Please split long expressions into a sequence of smaller expressions.\")\n }\n\n code <- str_flatten_lines(lines)\n if (preserve_attributes)\n attributes(code) <- attrs_in\n code\n}\n\n"], ["/quickr/R/aaa-utils.R", "#' @importFrom glue glue glue_data trim as_glue glue_collapse single_quote\n#' @importFrom dotty .\n#' @importFrom stats setNames\n#' @importFrom utils gethash hashtab remhash sethash str\nNULL\n\n# @export\n# This will be exported by S7 next release.\n`:=` <- function(left, right) {\n name <- substitute(left)\n if (!is.symbol(name))\n stop(\"left hand side must be a symbol\")\n\n right <- substitute(right)\n if (!is.call(right))\n stop(\"right hand side must be a call\")\n\n if (is.symbol(cl <- right[[1L]]) &&\n as.character(cl) %in% c(\"function\", \"new.env\")) {\n # attach \"name\" attr for usage like:\n # foo := function(){}\n # foo := new.env()\n right <- eval(right, parent.frame())\n attr(right, \"name\") <- as.character(name)\n } else {\n # for all other usage,\n # inject name as a named arg, so that\n # foo := new_class(...)\n # becomes\n # foo <- new_class(..., name = \"foo\")\n\n right <- as.call(c(as.list(right), list(name = as.character(name))))\n\n ## skip check; if duplicate 'name' arg is an issue the call itself will signal an error.\n # if (hasName(right, \"name\")) stop(\"duplicate `name` argument.\")\n\n ## alternative code path that injects `name` as positional arg instead\n # right <- as.list(right)\n # right <- as.call(c(right[[1L]], as.character(name), right[-1L]))\n }\n\n eval(call(\"<-\", name, right), parent.frame())\n}\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\n`append<-` <- function(x, after, value) {\n if (missing(after))\n c(x, value)\n else\n append(x, value, after = after)\n}\n\n`append1<-` <- function (x, value) {\n stopifnot(is.list(x) || identical(mode(x), mode(value)))\n x[[length(x) + 1L]] <- value\n x\n}\n\n`prepend<-` <- function(x, value) {\n c(vector(typeof(x)), value, x)\n}\n\n`add<-` <- `+` #function(x, value) x + value\n\nmap_int <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = 0L, ...)\nmap_lgl <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)\nmap_chr <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = \"\", ...)\n\nimap <- function (.x, .f, ...) {\n out <- .mapply(.f, list(.x, names(.x) %||% seq_along(.x)),\n list(...))\n names(out) <- names(.x)\n out\n}\n\nmap2 <- function (.x, .y, .f, ...) {\n if (length(.x) != length(.y) && length(.x) != 1L && length(.y) != 1L)\n stop(\".x and .y must have the same length, or one of them must have length 1\")\n out <- .mapply(.f, list(.x, .y), list(...))\n if (length(.x) == length(out))\n names(out) <- names(.x)\n out\n}\n\ndiscard <- function(.x, .f, ...)\n .x[!vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\nkeep <- function(.x, .f, ...)\n .x[vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\ncompact <- function(.x)\n .x[as.logical(lengths(.x, use.names = FALSE))]\n\ndrop_nulls <- function(x, i) {\n if (missing(i))\n x[!vapply( X = x, FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)]\n else {\n drop <- logical(length(x))\n names(drop) <- names(x)\n drop[i] <- vapply(X = x[i], FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)\n x[!drop]\n }\n}\n\nlast <- function(x) x[[length(x)]]\ndrop_last <- function(x) x[-length(x)]\n\nis_scalar_na <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && is.na(x)\nis_scalar_atomic <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_scalar_integer <- function(x) is.integer(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_string <- function(x) is.character(x) && length(x) == 1L && !is.na(x) # could also be 'glue' class.\nis_bool <- function(x) is.logical(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_number <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_wholenumber <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x) &&\n x >= 0L && (is.integer(x) || is.double(x) && trunc(x) == x)\n\nnew_function <- function(args = NULL, body = NULL, env = parent.frame()) {\n as.function.default(c(args, body %||% list(NULL)), env)\n}\n\nis_call <- function(x, name = NULL) {\n is.call(x) && (is.null(name) || identical(as.symbol(name), x[[1L]]))\n}\n\nstr_flatten <- function(x, collapse = \"\") {\n paste0(as.character(unlist(x, use.names = FALSE)), collapse = collapse)\n}\n\nstr_flatten_lines <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \"\\n\")\n}\n\nstr_flatten_commas <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \", \")\n}\n\nstr_flatten_args <- function(..., multiline = length(dots) >= 3) {\n dots <- unlist(c(character(), ...), use.names = FALSE)\n if (multiline) {\n dots <- paste0(\"\\n \", dots, collapse = \",\")\n paste(dots, \"\\n\")\n } else {\n paste0(dots, collapse = \",\")\n }\n}\n\ninterleave <- function(x, y) {\n stopifnot(is.atomic(x), is.atomic(y), length(y) == 1L, typeof(x) == typeof(y))\n drop_last(as.vector(rbind(x, y, deparse.level = 0L)))\n}\n\nstr_split_lines <- function(...) {\n x <- c(...) |>\n unlist(use.names = FALSE) |>\n strsplit(\"\\n\", fixed = TRUE)\n x[!lengths(x)] <- \"\"\n x |>\n unlist(use.names = FALSE) |>\n trimws(\"right\")\n}\n\nindent <- function(x, n = 2L) {\n x <- str_split_lines(x)\n x <- sub(\"[ \\t\\r]+$\", \"\", x, perl = TRUE) # trim trailing whitespace\n paste0(strrep(\" \", n), x, collapse = \"\\n\")\n}\n\nparent.pkg <- function(env = parent.frame(2)) {\n if (isNamespace(env <- topenv(env)))\n as.character(getNamespaceName(env)) # unname\n else\n NULL # print visible\n}\n\nset_names <- function(x, nm = x, ...) {\n names(x) <- as.character(\n if (is.function(nm)) nm(names(x), ...)\n else unlist(list(nm, ...), use.names = FALSE)\n )\n x\n}\n\nzip_lists <- function(...) {\n x <- if (...length() == 1L) ..1 else list(...)\n\n if (is.character(nms.1 <- names(x.1 <- x[[1L]])))\n if (anyDuplicated(nms.1) || anyNA(nms.1) || any(nms.1 == \"\"))\n stop(\"All names must be unique.\",\n \" (Use `unname()` for positional matching.)\")\n\n if (length(setdiff(lengths(x), 1L)) != 1L)\n stop(\"all elements must have the same length\")\n\n for (i in seq_along(x)) {\n if (identical(nms.1, nms.i <- names(x[[i]])))\n next\n if (setequal(nms.1, nms.i)) {\n x[[i]] <- x[[i]][nms.1]\n next\n }\n stop(\"All names of arguments provided to `zip_lists()` must match.\",\n \" Call `unname()` on each argument if you want positional matching\")\n }\n ans <- .mapply(list, x, NULL)\n names(ans) <- nms.1\n ans\n}\n\nis_missing <- function(x) missing(x) || identical(x, quote(expr = ))\n\nis_type_call <- function(e) {\n is.call(e) && identical(e[[1]], quote(type))\n}\n\nreduce <- function (.x, .f, ..., .init) {\n f <- function(x, y) .f(x, y, ...)\n Reduce(f, .x, init = .init)\n}\n\nsubstitute_ <- function(expr, env) {\n do.call(base::substitute, list(expr, env))\n}\n\ndefer <- function (expr, env = parent.frame(), after = FALSE) {\n thunk <- as.call(list(function() expr))\n do.call(on.exit, list(thunk, TRUE, after), envir = env)\n}\n\nis_scalar <- function(x) identical(length(x), 1L)\n"], ["/quickr/R/quick.R", "#' Compile a Quick Function\n#'\n#' Compile an R function.\n#'\n#' @param fun An R function\n#' @param name Optional string, name to use for the function.\n#'\n#' @details\n#'\n#' ## `declare(type())` syntax:\n#'\n#' The shape and mode of all function arguments must be declared. Local and\n#' return variables may optionally also be declared.\n#'\n#' `declare(type())` also has support for declaring size constraints, or size\n#' relationships between variables. Here are some examples of declare calls:\n#'\n#' ```r\n#' declare(type(x = double(NA))) # x is a 1-d double vector of any length\n#' declare(type(x = double(10))) # x is a 1-d double vector of length 10\n#' declare(type(x = double(1))) # x is a scalar double\n#'\n#' declare(type(x = integer(2, 3))) # x is a 2-d integer matrix with dim (2, 3)\n#' declare(type(x = integer(NA, 3))) # x is a 2-d integer matrix with dim (<any>, 3)\n#'\n#' # x is a 4-d logical matrix with dim (<any>, 24, 24, 3)\n#' declare(type(x = logical(NA, 24, 24, 3)))\n#'\n#' # x and y are 1-d double vectors of any length\n#' declare(type(x = double(NA)),\n#' type(y = double(NA)))\n#'\n#' # x and y are 1-d double vectors of the same length\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' # x and y are 1-d double vectors, where length(y) == length(x) + 2\n#' declare(type(x = double(n)),\n#' type(y = double(n+2)))\n#' ```\n#'\n#' You can provide declarations to `declare()` as:\n#'\n#' - Multiple arguments to a single `declare()` call\n#' - Separate `declare()` calls\n#' - Multiple arguments within a code block (`{}`) inside `declare()`\n#'\n#' ```r\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' declare(type(x = double(n)))\n#' declare(type(y = double(n)))\n#'\n#' declare({\n#' type(x = double(n))\n#' type(y = double(n))\n#' })\n#' ```\n#'\n#' ## Return values\n#'\n#' The shape and type of a function return value must be known at compile time.\n#' In most situations, this will be automatically inferred by `quick()`. However,\n#' if the output is dynamic, then you may need to provide a hint.\n#' For example, returning the result of `seq()` will fail because the output shape\n#' cannot be inferred.\n#'\n#' ```r\n#' # Will fail to compile:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' ```\n#'\n#' However, if the output size can be declared as a dynamic expression using other\n#' values known at runtime, compilation will succeed:\n#'\n#' ```r\n#' # Succeeds:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' type(out = integer(end - start + 1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' quick_seq(1L, 5L)\n#' ```\n#'\n#' @returns A quicker R function.\n#' @export\n#' @examples\n#' add_ab <- quick(function(a, b) {\n#' declare(type(a = double(n)),\n#' type(b = double(n)))\n#' out <- a + b\n#' out\n#' })\n#' add_ab(1, 2)\nquick <- function(fun, name = NULL) {\n if (is.null(name)) {\n name <- if (is.symbol(substitute(fun)))\n deparse(substitute(fun))\n else\n make_unique_name(prefix = \"anonymous_quick_function_\")\n }\n\n if (nzchar(pkgname <- Sys.getenv(\"DEVTOOLS_LOAD\"))) {\n if (!collector$is_active()) {\n if (!requireNamespace(\"pkgload\", quietly = TRUE)) {\n stop(\"Please install 'pkgload'\")\n }\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_code)) {\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n defer(dump_collected(), sys.frame(i), after = TRUE)\n break\n }\n }\n }\n }\n\n if (collector$is_active()) {\n # we are in a quickr::compile_package() or a devtools::load_all() call,\n # merely collecting functions at this point.\n quick_closure <- create_quick_closure(name, fun)\n collector$add(name = name, closure = fun, quick_closure = quick_closure)\n return(quick_closure)\n }\n\n pkgname <- parent.pkg()\n if (!is.null(pkgname) && pkgname != \"quickr\") {\n # we are in a package - but outside a quickr::compile_package() call.\n return(create_quick_closure(name, fun))\n }\n\n # not in a package. Compile and load eagerly.\n attr(fun, \"name\") <- name\n fun <- compile(r2f(fun))\n attr(fun, \"name\") <- NULL\n\n fun\n}\n\ncompile <- function(fsub, build_dir = tempfile(paste0(fsub@name, \"-build-\"))) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n name <- fsub@name\n c_wrapper <- make_c_bridge(fsub)\n\n if (dir.exists(build_dir)) unlink(build_dir, recursive = T)\n if (!dir.exists(build_dir))\n dir.create(build_dir)\n owd <- setwd(build_dir)\n on.exit(setwd(owd))\n\n fsub_path <- paste0(name, \"_fsub.f90\")\n c_wrapper_path <- paste0(name, \"_c_wrapper.c\")\n dll_path <- paste0(name, .Platform$dynlib.ext)\n writeLines(fsub, fsub_path)\n writeLines(c_wrapper, c_wrapper_path)\n\n suppressWarnings({\n result <- system2(\n R.home(\"bin/R\"),\n c(\"CMD SHLIB --use-LTO\", \"-o\", dll_path, fsub_path, c_wrapper_path),\n stdout = TRUE, stderr = TRUE\n )\n })\n if (!is.null(attr(result, \"status\"))) {\n writeLines(result, stderr())\n str(attributes(result))\n stop(\"Compilation Error\")\n }\n\n # tryCatch(dyn.unload(dll_path), error = identity)\n dll <- dyn.load(dll_path)\n c_wrapper_name <- paste0(fsub@name, \"_\")\n ptr <- getNativeSymbolInfo(c_wrapper_name, dll)$address\n\n create_quick_closure(fsub@name, fsub@closure, native_symbol = ptr)\n}\n\n\n\ncreate_quick_closure <- function(name, closure,\n native_symbol = as.name(paste0(name, \"_\"))) {\n body(closure) <- as.call(c(quote(.External), native_symbol,\n lapply(names(formals(closure)), as.name)))\n closure\n}\n\n\n\ncheck_all_var_names_valid <- function(fun) {\n nms <- unique(c(names(formals(fun)), all.vars(body(fun), functions = FALSE)))\n invalid <- endsWith(nms, \"_\") | startsWith(nms, \"_\") | nms %in% c(\n\n # clashes with Fortran subroutine symbols\n \"c_int\", \"c_double\", \"c_ptrdiff_t\",\n\n # clashes with C bridge symbols\n \"int\" #, \"double\",\n\n # ??? (clashes with R symbols?)\n # \"double\", \"integer\"\n )\n if (any(invalid)) {\n stop(\"symbols cannot start or end with '_', but found: \",\n glue_collapse(invalid, \", \", last = \", and \"))\n }\n}\n\n\n\n# ---- utils ----\n\nmake_unique_name <- local({\n i <- 0L\n function(prefix = \"tmp\") {\n paste0(prefix, i <<- i + 1L)\n }\n})\n"], ["/quickr/R/compile-package.R", "\n\n\n#' Compile all `quick()` functions in a package.\n#'\n#' This will compile all `quick()` functions in an R package, and\n#' generate source files in the `src/` directory.\n#'\n#' Note, this function is automatically invoked during a `pkgload::load_all()` call.\n#'\n#' @param path Path to an R package\n#'\n#' @returns Called for its side effect.\n#' @export\ncompile_package <- function(path = \".\") {\n if (path != \".\") {\n owd <- setwd(path)\n on.exit(setwd(owd), add = TRUE)\n }\n\n if (!dir.exists(\"R\") || !file.exists(\"DESCRIPTION\"))\n stop(path, \" does not appear to be an R package.\")\n\n pkgname <- read.dcf(\"DESCRIPTION\", \"Package\")\n if (length(pkgname) != 1)\n stop(sprintf(\"path '%s' does not point to an R package\", path))\n pkgname <- as.character(pkgname)\n\n # collect all `quick()` calls in the package\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n\n # TODO: need to unset various R_* env vars, or just\n # take a dep on callr\n system2(file.path(R.home(\"bin\"), \"R\"),\n c(\"-q\", \"-e\", shQuote(\"pkgload::load_all()\")))\n}\n\n\ndump_collected <- function() {\n\n collected <- collector$get_collected()\n\n # try to resolve closure names for anonymous functions\n pkg_ns <- topenv(environment(collected[[1L]]$closure))\n pkg_funcs <- as.list.environment(pkg_ns, all.names = TRUE)\n tab <- hashtab(\"address\", length(collected))\n for (i in seq_along(pkg_funcs)) {\n if (typeof(fn <- pkg_funcs[[i]]) == \"closure\")\n # if is quick closure ...\n sethash(tab, pkg_funcs[[i]], names(pkg_funcs)[i])\n }\n\n quick_funcs <- unlist(recursive = FALSE, lapply(collected, function(x) {\n if (!startsWith(x$name, \"anonymous_quick_function_\"))\n return(setNames(list(x$closure), x$name))\n true_name <- gethash(tab, x$quick_closure)\n if (is.null(true_name))\n return(setNames(list(x$closure), x$name))\n # update pkg_ns with true name\n quick_closure <- create_quick_closure(true_name, x$closure)\n pkg_ns[[true_name]] <- quick_closure\n remhash(tab, x$quick_closure)\n setNames(list(x$closure), true_name)\n }))\n\n\n pkgname <- basename(normalizePath(\".\"))\n\n # check if we have a useDynLib line in NAMESPACE.\n if (!any(sapply(parse(file = \"NAMESPACE\"), function(e) {\n identical(e[[1]], quote(useDynLib)) && isTRUE(e$.registration)\n })))\n message(\"- Please add this roxygen directive somewhere in the Package R sources:\\n \",\n glue(\"#' @useDynLib {pkgname}, .registration = TRUE\"), \"\\n\",\n \"- Then run `devtools::document()`\\n\")\n\n sources <- zip_lists(imap(quick_funcs, function(func, name) {\n fsub <- new_fortran_subroutine(name, func)\n cbridge <- make_c_bridge(fsub, headers = name == names(quick_funcs)[1])\n list(f90 = fsub, c = cbridge)\n })) |> lapply(\\(x) x |> unlist() |> interleave(\"\\n\"))\n\n entries <- paste0(sprintf(' {\"%1$s\", (DL_FUNC) &%1$s, -1}',\n paste0(names(quick_funcs), \"_\")),\n collapse = \",\\n\")\n entries <- sprintf(\"static const R_ExternalMethodDef QuickrEntries[] = {\\n%s\\n};\",\n entries)\n\n append(sources$c) <- c(\"\", entries, \"\")\n\n R_init_pkg <- paste0(\"R_init_\", pkgname, \"(\")\n has_pkg_init_fn <- list.files(\"src\", pattern = \"\\\\.(c|cpp|h|hpp|c\\\\+\\\\+)$\",\n recursive = TRUE, all.files = TRUE,\n full.names = TRUE) |>\n setdiff(\"src/quickr_entrypoints.c\") |>\n lapply(function(f) {\n any(grepl(R_init_pkg, readLines(f, warn = FALSE), fixed = TRUE))\n }) |> unlist() |> any()\n\n append(sources$c) <- c(\"#include <R_ext/Rdynload.h>\", \"\")\n\n init_fn <- if (has_pkg_init_fn) {\n glue(\"\n void R_init_{pkgname}_quick_functions(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n }}\")\n } else {\n init_pkgname <- gsub(\".\", \"_\", pkgname, fixed = TRUE)\n glue(\"\n void R_init_{init_pkgname}(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n R_useDynamicSymbols(dll, FALSE);\n }}\")\n }\n\n append(sources$c) <- init_fn\n\n sources <- lapply(sources, str_split_lines)\n\n src_files_written <- FALSE\n if (!file.exists(\"src\")) dir.create(\"src\")\n cbridges_filepath <- \"src/quickr_entrypoints.c\"\n if (!file.exists(cbridges_filepath) || !identical(sources$c, readLines(cbridges_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(cbridges_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$c, cbridges_filepath)\n cli::cli_inform(c(i = \"Updated {.file {cbridges_filepath}}\"))\n src_files_written <- TRUE\n }\n\n fsubs_filepath <- \"src/quickr_sub_routines.f90\"\n if (!file.exists(fsubs_filepath) || !identical(sources$f90, readLines(fsubs_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(fsubs_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$f90, fsubs_filepath)\n cli::cli_inform(c(i = \"Updated {.file {fsubs_filepath}}\"))\n src_files_written <- TRUE\n }\n\n if (src_files_written) {\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_all)) {\n defer(pkgload::load_all(), sys.frame(i), after = TRUE)\n rlang::return_from(sys.frame(i), value = invisible())\n break\n }\n }\n }\n invisible()\n}\n\npkg_dll_path <- function (pkgname) {\n file.path(\"src\", paste0(pkgname, .Platform$dynlib.ext))\n}\n\n\ncollector <- local({\n\n .collected <- NULL\n\n activate <- function(name = NULL) {\n .collected <<- list()\n attr(.collected, \"name\") <<- name\n }\n\n is_active <- function() {\n is.list(.collected)\n }\n\n add <- function(...) {\n .collected[[length(.collected)+1L]] <<- list(...)\n }\n\n get_collected <- function(clear = TRUE) {\n if (clear)\n on.exit(.collected <<- NULL)\n .collected\n }\n\n environment()\n})\n"], ["/quickr/R/preprocess-lang.R", "\n\ndefuse_numeric_literals <- function(e) {\n if (is.call(e)) {\n e <- as.call(lapply(e, defuse_numeric_literals))\n if (is.symbol(e1 <- e[[1L]]) &&\n as.character(e1) %in% c(\"+\", \"-\", \"*\", \"/\", \"%%\", \"%/%\", \"^\") &&\n all(map_lgl(e[-1L], is.atomic))) {\n e <- eval(e, baseenv())\n }\n }\n e\n}\n\n\nensure_last_expr_sym <- function(bdy) {\n if (!is_call(bdy, quote(`{`)))\n stop(\"bad body, needs {\")\n if (!is.symbol(last_expr <- last(bdy))) {\n bdy[[length(bdy)]] <- call(\"<-\", quote(out_), last_expr)\n bdy[[length(bdy) + 1L]] <- quote(out_)\n }\n bdy\n}\n\n\nwhole_doubles_to_ints <- function(x) {\n walker <- function(x) {\n switch(\n typeof(x),\n double = if (trunc(x) == x) as.integer(x),\n language = as.call(lapply(x, walker)),\n list = lapply(x, walker),\n x\n )\n }\n walker(x)\n}\n"], ["/quickr/R/scope.R", "\n\nnew_ordered_env <- function(parent = emptyenv()) {\n env <- new.env(parent = parent)\n class(env) <- \"quickr_ordered_env\"\n env\n}\n\n#' @export\n`[[<-.quickr_ordered_env` <- function(x, name, value) {\n attr(x, \"ordered_names\") <- unique(c(attr(x, \"ordered_names\", TRUE), name))\n assign(name, value, envir = x)\n x\n # NextMethod()\n}\n\n#' @export\n`[[.quickr_ordered_env` <- function(x, name) {\n get0(name, x) # name can be a symbols too\n}\n\n#' @export\nnames.quickr_ordered_env <- function(x) {\n all_names <- ls(envir = x, sorted = FALSE)\n ordered_names <- attr(x, \"ordered_names\", TRUE)\n if (!setequal(all_names, ordered_names)) {\n warning(\"untracked name\")\n stop(\"untracked name\")\n }\n ordered_names\n}\n\n#' @export\nas.list.quickr_ordered_env <- function(x, ...) {\n out <- as.list.environment(x, all.names = TRUE, ...)\n out[names.quickr_ordered_env(x)]\n}\n\n#' @export\nprint.quickr_ordered_env <- function(x, ...) {\n emit(\"env (class: \", str_flatten_commas(class(x)), \") with bindings:\")\n str(as.list.quickr_ordered_env(x), no.list = TRUE)\n}\n\n\ncheck_assignment_compatible <- function(target, value) {\n if (is.null(value)) return()\n stopifnot(exprs = {\n inherits(target, Variable)\n inherits(value, Variable)\n passes_as_scalar(target) || passes_as_scalar(value) || target@rank == value@rank\n })\n}\n\nnew_scope <- function(closure, parent = emptyenv()) {\n scope <- new_ordered_env(parent = parent)\n class(scope) <- unique(c(\"quickr_scope\", class(scope)))\n attr(scope, \"closure\") <- closure\n\n\n attr(scope, \"get_unique_var\") <- local({\n i <- 0L\n function(...) {\n name <- paste0(\"tmp\", i <<- i + 1L, \"_\")\n (scope[[name]] <- Variable(..., name = name))\n }\n })\n attr(scope, \"assign\") <- function(name, value) {\n stopifnot(inherits(value, Variable), is.symbol(name) || is_string(name))\n name <- as.character(name)\n if (exists(name, scope))\n check_assignment_compatible(get(name, scope), value)\n value@name <- name\n assign(name, value, scope)\n }\n scope\n}\n\n\n#' @export\n`@.quickr_scope` <- function(x, name) attr(x, name, exact = TRUE)\n\n#' @export\n`@<-.quickr_scope` <- function(x, name, value) `attr<-`(x, name, value = value)\n\n#' @importFrom utils .AtNames findMatches\n#' @export\n.AtNames.quickr_scope <- function(x, pattern = \"\")\n findMatches(pattern, names(attributes(x)))\n\n"], ["/quickr/R/zzz.R", "# # ' @export\n# `@.default` <- function(x, name) {\n# if (isS4(x))\n# methods::slot(x, name)\n# else\n# attr(x, name, TRUE)\n# }\n#\n# # ' @export\n# `@<-.default` <- function(x, name, value) {\n# if (isS4(x))\n# methods::`slot<-`(x, name, value = value)\n# else\n# `attr<-`(x, name, value)\n# }\n#\n# # ' @importFrom utils .AtNames findMatches\n# .AtNames.default <- function(x, pattern = \"\") {\n# if (isS4(x))\n# findMatches(pattern, methods::slotNames(x))\n# else\n# findMatches(pattern, names(attributes(x)))\n# }\n#\n# on_load_register_.AtNames.default <- function() {\n# # if we register via NAMESPACE, we get warning\n# # about overwriting utils:::.AtNmaes.default\n# registerS3method(\".AtNames\", \"default\", .AtNames.default)\n# }\n\n.onLoad <- function(...) {\n S7::methods_register()\n asNamespace(\"dotty\")$dotify()\n # on_load_register_.AtNames.default()\n}\n\n"]], "task_instance_info": {"created_time": "2025-08-21 01:15:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(size, axis) {}", "code_description": "This code segment functions to: Resolve dimension size specifications by mapping symbolic references to generated identifiers, handling numeric constants, and managing placeholder values for dynamic axis-based naming conventions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(size, axis) {\n get_size_name(var, axis)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-16-22"}, "editdistance_info": {"edit_distance": 12.766, "calculate_time": "2025-08-21 01:16:22", "true_code_clean": "function(size, axis) {\n size_name <- as.symbol(get_size_name(var, axis))\n if (is.symbol(size) && !exists(size, aliases)) {\n assign(as.character(size), size_name, aliases)\n size <- size_name\n } else if (is_scalar_na(size)) {\n size <- size_name\n } else if (is_wholenumber(size)) {\n size <- as.integer(size)\n }\n size\n }", "predict_code_clean": "function(size, axis) {\n get_size_name(var, axis)\n}"}}
{"repo_name": "quickr", "file_name": "/quickr/R/scope.R", "inference_info": {"prefix_code": "\n\nnew_ordered_env <- function(parent = emptyenv()) {\n env <- new.env(parent = parent)\n class(env) <- \"quickr_ordered_env\"\n env\n}\n\n#' @export\n`[[<-.quickr_ordered_env` <- function(x, name, value) {\n attr(x, \"ordered_names\") <- unique(c(attr(x, \"ordered_names\", TRUE), name))\n assign(name, value, envir = x)\n x\n # NextMethod()\n}\n\n#' @export\n`[[.quickr_ordered_env` <- function(x, name) {\n get0(name, x) # name can be a symbols too\n}\n\n#' @export\nnames.quickr_ordered_env <- function(x) {\n all_names <- ls(envir = x, sorted = FALSE)\n ordered_names <- attr(x, \"ordered_names\", TRUE)\n if (!setequal(all_names, ordered_names)) {\n warning(\"untracked name\")\n stop(\"untracked name\")\n }\n ordered_names\n}\n\n#' @export\nas.list.quickr_ordered_env <- function(x, ...) {\n out <- as.list.environment(x, all.names = TRUE, ...)\n out[names.quickr_ordered_env(x)]\n}\n\n#' @export\nprint.quickr_ordered_env <- function(x, ...) {\n emit(\"env (class: \", str_flatten_commas(class(x)), \") with bindings:\")\n str(as.list.quickr_ordered_env(x), no.list = TRUE)\n}\n\n\ncheck_assignment_compatible <- function(target, value) {\n if (is.null(value)) return()\n stopifnot(exprs = {\n inherits(target, Variable)\n inherits(value, Variable)\n passes_as_scalar(target) || passes_as_scalar(value) || target@rank == value@rank\n })\n}\n\nnew_scope <- ", "suffix_code": "\n\n\n#' @export\n`@.quickr_scope` <- function(x, name) attr(x, name, exact = TRUE)\n\n#' @export\n`@<-.quickr_scope` <- function(x, name, value) `attr<-`(x, name, value = value)\n\n#' @importFrom utils .AtNames findMatches\n#' @export\n.AtNames.quickr_scope <- function(x, pattern = \"\")\n findMatches(pattern, names(attributes(x)))\n\n", "middle_code": "function(closure, parent = emptyenv()) {\n scope <- new_ordered_env(parent = parent)\n class(scope) <- unique(c(\"quickr_scope\", class(scope)))\n attr(scope, \"closure\") <- closure\n attr(scope, \"get_unique_var\") <- local({\n i <- 0L\n function(...) {\n name <- paste0(\"tmp\", i <<- i + 1L, \"_\")\n (scope[[name]] <- Variable(..., name = name))\n }\n })\n attr(scope, \"assign\") <- function(name, value) {\n stopifnot(inherits(value, Variable), is.symbol(name) || is_string(name))\n name <- as.character(name)\n if (exists(name, scope))\n check_assignment_compatible(get(name, scope), value)\n value@name <- name\n assign(name, value, scope)\n }\n scope\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/quickr/R/aaa-utils.R", "#' @importFrom glue glue glue_data trim as_glue glue_collapse single_quote\n#' @importFrom dotty .\n#' @importFrom stats setNames\n#' @importFrom utils gethash hashtab remhash sethash str\nNULL\n\n# @export\n# This will be exported by S7 next release.\n`:=` <- function(left, right) {\n name <- substitute(left)\n if (!is.symbol(name))\n stop(\"left hand side must be a symbol\")\n\n right <- substitute(right)\n if (!is.call(right))\n stop(\"right hand side must be a call\")\n\n if (is.symbol(cl <- right[[1L]]) &&\n as.character(cl) %in% c(\"function\", \"new.env\")) {\n # attach \"name\" attr for usage like:\n # foo := function(){}\n # foo := new.env()\n right <- eval(right, parent.frame())\n attr(right, \"name\") <- as.character(name)\n } else {\n # for all other usage,\n # inject name as a named arg, so that\n # foo := new_class(...)\n # becomes\n # foo <- new_class(..., name = \"foo\")\n\n right <- as.call(c(as.list(right), list(name = as.character(name))))\n\n ## skip check; if duplicate 'name' arg is an issue the call itself will signal an error.\n # if (hasName(right, \"name\")) stop(\"duplicate `name` argument.\")\n\n ## alternative code path that injects `name` as positional arg instead\n # right <- as.list(right)\n # right <- as.call(c(right[[1L]], as.character(name), right[-1L]))\n }\n\n eval(call(\"<-\", name, right), parent.frame())\n}\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\n`append<-` <- function(x, after, value) {\n if (missing(after))\n c(x, value)\n else\n append(x, value, after = after)\n}\n\n`append1<-` <- function (x, value) {\n stopifnot(is.list(x) || identical(mode(x), mode(value)))\n x[[length(x) + 1L]] <- value\n x\n}\n\n`prepend<-` <- function(x, value) {\n c(vector(typeof(x)), value, x)\n}\n\n`add<-` <- `+` #function(x, value) x + value\n\nmap_int <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = 0L, ...)\nmap_lgl <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)\nmap_chr <- function(.x, .f, ...) vapply(X = .x, FUN = .f, FUN.VALUE = \"\", ...)\n\nimap <- function (.x, .f, ...) {\n out <- .mapply(.f, list(.x, names(.x) %||% seq_along(.x)),\n list(...))\n names(out) <- names(.x)\n out\n}\n\nmap2 <- function (.x, .y, .f, ...) {\n if (length(.x) != length(.y) && length(.x) != 1L && length(.y) != 1L)\n stop(\".x and .y must have the same length, or one of them must have length 1\")\n out <- .mapply(.f, list(.x, .y), list(...))\n if (length(.x) == length(out))\n names(out) <- names(.x)\n out\n}\n\ndiscard <- function(.x, .f, ...)\n .x[!vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\nkeep <- function(.x, .f, ...)\n .x[vapply(X = .x, FUN = .f, FUN.VALUE = TRUE, ...)]\n\ncompact <- function(.x)\n .x[as.logical(lengths(.x, use.names = FALSE))]\n\ndrop_nulls <- function(x, i) {\n if (missing(i))\n x[!vapply( X = x, FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)]\n else {\n drop <- logical(length(x))\n names(drop) <- names(x)\n drop[i] <- vapply(X = x[i], FUN = is.null, FUN.VALUE = FALSE, USE.NAMES = FALSE)\n x[!drop]\n }\n}\n\nlast <- function(x) x[[length(x)]]\ndrop_last <- function(x) x[-length(x)]\n\nis_scalar_na <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && is.na(x)\nis_scalar_atomic <- function(x) is.atomic(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_scalar_integer <- function(x) is.integer(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_string <- function(x) is.character(x) && length(x) == 1L && !is.na(x) # could also be 'glue' class.\nis_bool <- function(x) is.logical(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_number <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x)\nis_wholenumber <- function(x) is.numeric(x) && !is.object(x) && length(x) == 1L && !is.na(x) &&\n x >= 0L && (is.integer(x) || is.double(x) && trunc(x) == x)\n\nnew_function <- function(args = NULL, body = NULL, env = parent.frame()) {\n as.function.default(c(args, body %||% list(NULL)), env)\n}\n\nis_call <- function(x, name = NULL) {\n is.call(x) && (is.null(name) || identical(as.symbol(name), x[[1L]]))\n}\n\nstr_flatten <- function(x, collapse = \"\") {\n paste0(as.character(unlist(x, use.names = FALSE)), collapse = collapse)\n}\n\nstr_flatten_lines <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \"\\n\")\n}\n\nstr_flatten_commas <- function(...) {\n paste0(unlist(c(character(), ...), use.names = FALSE), collapse = \", \")\n}\n\nstr_flatten_args <- function(..., multiline = length(dots) >= 3) {\n dots <- unlist(c(character(), ...), use.names = FALSE)\n if (multiline) {\n dots <- paste0(\"\\n \", dots, collapse = \",\")\n paste(dots, \"\\n\")\n } else {\n paste0(dots, collapse = \",\")\n }\n}\n\ninterleave <- function(x, y) {\n stopifnot(is.atomic(x), is.atomic(y), length(y) == 1L, typeof(x) == typeof(y))\n drop_last(as.vector(rbind(x, y, deparse.level = 0L)))\n}\n\nstr_split_lines <- function(...) {\n x <- c(...) |>\n unlist(use.names = FALSE) |>\n strsplit(\"\\n\", fixed = TRUE)\n x[!lengths(x)] <- \"\"\n x |>\n unlist(use.names = FALSE) |>\n trimws(\"right\")\n}\n\nindent <- function(x, n = 2L) {\n x <- str_split_lines(x)\n x <- sub(\"[ \\t\\r]+$\", \"\", x, perl = TRUE) # trim trailing whitespace\n paste0(strrep(\" \", n), x, collapse = \"\\n\")\n}\n\nparent.pkg <- function(env = parent.frame(2)) {\n if (isNamespace(env <- topenv(env)))\n as.character(getNamespaceName(env)) # unname\n else\n NULL # print visible\n}\n\nset_names <- function(x, nm = x, ...) {\n names(x) <- as.character(\n if (is.function(nm)) nm(names(x), ...)\n else unlist(list(nm, ...), use.names = FALSE)\n )\n x\n}\n\nzip_lists <- function(...) {\n x <- if (...length() == 1L) ..1 else list(...)\n\n if (is.character(nms.1 <- names(x.1 <- x[[1L]])))\n if (anyDuplicated(nms.1) || anyNA(nms.1) || any(nms.1 == \"\"))\n stop(\"All names must be unique.\",\n \" (Use `unname()` for positional matching.)\")\n\n if (length(setdiff(lengths(x), 1L)) != 1L)\n stop(\"all elements must have the same length\")\n\n for (i in seq_along(x)) {\n if (identical(nms.1, nms.i <- names(x[[i]])))\n next\n if (setequal(nms.1, nms.i)) {\n x[[i]] <- x[[i]][nms.1]\n next\n }\n stop(\"All names of arguments provided to `zip_lists()` must match.\",\n \" Call `unname()` on each argument if you want positional matching\")\n }\n ans <- .mapply(list, x, NULL)\n names(ans) <- nms.1\n ans\n}\n\nis_missing <- function(x) missing(x) || identical(x, quote(expr = ))\n\nis_type_call <- function(e) {\n is.call(e) && identical(e[[1]], quote(type))\n}\n\nreduce <- function (.x, .f, ..., .init) {\n f <- function(x, y) .f(x, y, ...)\n Reduce(f, .x, init = .init)\n}\n\nsubstitute_ <- function(expr, env) {\n do.call(base::substitute, list(expr, env))\n}\n\ndefer <- function (expr, env = parent.frame(), after = FALSE) {\n thunk <- as.call(list(function() expr))\n do.call(on.exit, list(thunk, TRUE, after), envir = env)\n}\n\nis_scalar <- function(x) identical(length(x), 1L)\n"], ["/quickr/R/r2f.R", "\n\n\n# Take parsed R code (anything returnable by base::str2lang()) and returns\n# a Fortran object, which is a string of Fortran code and some attributes\n# describing the value.\nlang2fortran <- r2f <- function(e, scope = NULL, ..., calls = character(), hoist = NULL) {\n ## 'hoist()' is a function that individual handlers can call to pre-emit some\n ## Fortran code. E.g., to setup a temporary variable if the generated Fortran\n ## code doesn't neatly translate into a single expression.\n hoisted <- character()\n if (is.null(hoist)) {\n delayedAssign(\"hoist_connection\", textConnection(\"hoisted\", \"w\", TRUE))\n hoist <- function(...) {\n writeLines(as.character(unlist(c(character(), ...))),\n hoist_connection)\n }\n # if performance with textConnection() becomes an issue, maybe switch to an\n # anonymous file(), though, each hoisting context is typically shortlived and\n # usually 0 lines are hoisted per context, and if they are hoisted, a small number.\n }\n\n fortran <- switch(typeof(e),\n language = {\n # a call\n handler <- get_r2f_handler(callable <- e[[1L]])\n\n match.fun <- attr(handler, \"match.fun\", TRUE)\n if (is.null(match.fun)) {\n match.fun <- get0(callable, parent.env(globalenv()),\n mode = \"function\")\n # this is a best effort to, eg. resolve `seq.default` from `seq`.\n # This should likely be moved into attaching the `match.fun` attr\n # to handlers, for more involved resolution (e.g., with getS3Method())\n if (\"UseMethod\" %in% all.names(body(match.fun)))\n match.fun <- get0(paste0(callable, \".default\"),\n parent.env(globalenv()),\n mode = \"function\",\n ifnotfound = match.fun)\n }\n if (typeof(match.fun) == \"closure\") {\n e <- match.call(match.fun, e)\n }\n\n if (isTRUE(getOption(\"quickr.r2f.debug\"))) {\n\n try(handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)) -> res\n if (inherits(res, \"try-error\")) {\n debugonce(handler)\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n }\n\n res\n\n } else {\n\n handler(as.list(e)[-1L], scope, ...,\n calls = c(calls, as.character(callable)),\n hoist = hoist)\n\n }\n\n },\n\n integer = ,\n double = ,\n complex = ,\n logical = atomic2Fortran(e),\n\n symbol = {\n s <- as.character(e)\n # logicals that come in from R are passed as integer types,\n # so for all fortran ops we cast to logical with /=0\n if (\n !is.null(scope[[e]] -> val) &&\n val@mode == \"logical\" &&\n val@is_external\n ) {\n s <- paste0(\"(\", s, \"/=0)\")\n }\n Fortran(s, value = scope[[e]])\n },\n\n ## handling 'object' and 'closure' here are both bad ideas,\n ## TODO: delete both\n # \"object\" = {\n # if (inherits(e, Variable))\n # e <- Fortran(character(), e)\n # stopifnot(inherits(e, Fortran))\n # e\n # },\n\n closure = {\n if (is.null(name <- attr(e, \"name\", TRUE))) {\n name <- if (is.symbol(name <- substitute(e)))\n as.character(name)\n else\n \"anonymous_function\"\n }\n\n stopifnot(is.null(scope))\n new_fortran_subroutine(name, e)\n },\n\n ## all the other typeof() possible values\n # \"character\",\n # \"raw\" ,\n # \"list\",\n # \"NULL\",\n # \"function\",\n # \"special\",\n # \"builtin\",\n # \"environment\",\n # \"S4\",\n # \"pairlist\",\n # \"promise\",\n # \"char\",\n # \"...\",\n # \"any\",\n # \"expression\",\n # \"externalptr\",\n # \"bytecode\",\n # \"weakref\"\n # default\n stop(\"Unsupported object type encountered: \", typeof(e))\n )\n\n if (length(hoisted)) {\n combined <- str_flatten_lines(c(hoisted, fortran))\n attributes(combined) <- attributes(fortran)\n fortran <- combined\n }\n\n attr(fortran, \"r\") <- e\n fortran\n}\n\n\natomic2Fortran <- function(x) {\n stopifnot(is_scalar_atomic(x))\n s <- switch(typeof(x),\n double =,\n integer = num2fortran(x),\n logical = if (x) \".true.\" else \".false.\",\n complex = sprintf(\"(%s, %s)\", num2fortran(Re(x)), num2fortran(Im(x))))\n Fortran(s, Variable(typeof(x)))\n}\n\nnum2fortran <- function(x) {\n stopifnot(typeof(x) %in% c(\"integer\", \"double\"))\n digits <- 7L\n nsmall <- switch(typeof(x), integer = 0L, double = 1L)\n repeat {\n s <- format.default(x, digits = digits, nsmall = nsmall, scientific = 1L)\n if (x == eval(str2lang(s))) # eval() needed for negative and complex numbers\n break\n add(digits) <- 1L\n if (digits > 22L)\n stop(\"number formatting error: \", x, \" formatted as : \", s)\n }\n paste0(s, switch(typeof(x), double = \"_c_double\", integer = \"_c_int\"))\n}\n\n\nr2f_handlers := new.env(parent = emptyenv())\n\nget_r2f_handler <- function(name) {\n stopifnot(\"All functions called must be named as symbols\" = is.symbol(name))\n get0(name, r2f_handlers) %||% stop(\"Unsupported function: \", name, call. = FALSE)\n}\n\nr2f_default_handler <- function(args, scope = NULL, ..., calls) {\n # stopifnot(is.call(e), is.symbol(e[[1L]]))\n\n x <- lapply(args, r2f, scope = scope, calls = calls, ...)\n s <- sprintf(\"%s(%s)\", last(calls), str_flatten_commas(x[-1]))\n Fortran(s)\n}\n\n## ??? export as S7::convert() methods?\nregister_r2f_handler <- function(name, fun) {\n stopifnot(\n is_string(name),\n identical(formals(fun), alist(x = , scope = NULL))\n )\n\n r2f_handlers[[name]] <- fun\n}\n\n.r2f_handler_not_implemented_yet <- function(e, scope, ...) {\n stop(gettextf(\"'%s' is not implemented yet\", as.character(e[[1L]])),\n call. = FALSE)\n}\n\nr2f_handlers[[\"declare\"]] <- function(args, scope, ...) {\n\n for (a in args) {\n if (is_missing(a)) {\n next\n }\n if (is_type_call(a)) {\n var <- type_call_to_var(a)\n var@is_arg <- var@name %in% names(formals(scope@closure))\n scope[[var@name]] <- var\n } else if (is_call(a, quote(`{`))) {\n Recall(as.list(a)[-1], scope)\n }\n }\n\n Fortran(\"\")\n}\n\n\nr2f_handlers[[\"Fortran\"]] <- function(args, scope = NULL, ...) {\n if (!is_string(args[[1]]))\n stop(\"Fortran() must be called with a string\")\n Fortran(args[[1]])\n # enable passing through literal fortran code\n # used like:\n # Fortran(\"nearest(x, 1)\", double(length(x)))\n # Fortran(\"nearest(x, 1)\", x)\n # Fortran(\"x = nearest(x, 1)\")\n}\n\nr2f_handlers[[\"(\"]] <- function(args, scope, ...) {\n r2f(args[[1L]], scope, ...)\n}\n\nr2f_handlers[[\"{\"]] <- function(args, scope, ..., hoist = NULL) {\n # every top level R-expr / fortran statement gets its own hoist target.\n x <- lapply(args, r2f, scope, ...)\n code <- str_flatten_lines(x)\n\n # browser()\n value <- (if (length(args)) last(x)@value) %||% Variable()\n Fortran(code, value)\n}\n\n\n\n# ---- reduction intrinsics ----\n\n\ncreate_mask_hoist <- function() {\n .hoisted_mask <- NULL\n\n try_set <- function(mask) {\n stopifnot(inherits(mask, Fortran), mask@value@mode == \"logical\")\n # each hoist can only accept one mask.\n if (is.null(.hoisted_mask)) {\n .hoisted_mask <<- mask\n return(TRUE)\n }\n # if the mask is identical, we accept it.\n if (identical(.hoisted_mask, mask)) {\n return(TRUE)\n }\n # can't hoist this mask.\n FALSE\n }\n\n get_hoisted <- function() .hoisted_mask\n\n environment()\n}\n\n\nr2f_handlers[[\"max\"]] <-\nr2f_handlers[[\"min\"]] <-\nr2f_handlers[[\"sum\"]] <-\nr2f_handlers[[\"prod\"]] <- function(args, scope, ...) {\n intrinsic <- switch(last(list(...)$calls),\n max = \"maxval\",\n min = \"minval\",\n sum = \"sum\",\n prod = \"product\")\n\n reduce_arg <- function(arg) {\n mask_hoist <- create_mask_hoist()\n x <- r2f(arg, scope, ..., hoist_mask = mask_hoist$try_set)\n if(x@value@rank == 0)\n return(x)\n hoisted_mask <- mask_hoist$get_hoisted()\n s <- glue(\n if (is.null(hoisted_mask))\n \"{intrinsic}({x})\"\n else\n \"{intrinsic}({x}, mask = {hoisted_mask})\"\n )\n Fortran(s, Variable(x@value@mode))\n }\n\n if (length(args) == 1) {\n reduce_arg(args[[1]])\n } else {\n args <- lapply(args, reduce_arg)\n mode <- reduce_promoted_mode(args)\n s <- switch(last(list(...)$calls),\n max = glue(\"max({str_flatten_commas(args)})\"),\n min = glue(\"min({str_flatten_commas(args)})\"),\n sum = glue(\"({str_flatten(args, ' + ')})\"),\n prod = glue(\"({str_flatten(args, ' * ')})\")\n )\n Fortran(s, Variable(mode))\n }\n}\n\n\nr2f_handlers[[\"which.max\"]] <-\nr2f_handlers[[\"which.min\"]] <-\nfunction(args, scope = NULL, ...) {\n stopifnot(length(args) == 1)\n x <- r2f(args[[1L]], scope, ...)\n stopifnot(\"Values passed to which.max()/which.min() must be 1d arrays\" = x@value@rank == 1)\n valout <- Variable(mode = \"integer\") # integer scalar\n\n if (x@value@mode == \"logical\") {\n val <- switch(last(list(...)$calls),\n which.max = \".true.\",\n which.min = \".false.\")\n f <- glue(\"findloc({x}, {val}, 1)\")\n } else {\n intrinsic <- switch(last(list(...)$calls),\n which.max = \"maxloc\",\n which.min = \"minloc\")\n f <- glue(\"{intrinsic}({x}, 1)\")\n }\n\n Fortran(f, valout)\n}\n\n\nr2f_handlers[[\"[\"]] <- function(args, scope, ..., hoist_mask = function(mask) FALSE) {\n\n # only a subset of R's x[...] features can be translated here. `...` can only be:\n # - a single logical mask, of the same rank as `x`. returns a rank 1 vector.\n # - a number of arguments matching the rank of `x`, with each being\n # an integer of rank 0 or 1. In this case, a rank 1 logical becomes\n # converted to an integer with\n\n var <- args[[1]]\n var <- r2f(var, scope, ...)\n\n idxs <- whole_doubles_to_ints(args[-1])\n idxs <- imap(idxs, function(idx, i) {\n if (is_missing(idx))\n Fortran(\":\", Variable(\"integer\", var@value@dims[[i]]))\n else\n r2f(idx, scope, ...)\n })\n\n if (length(idxs) == 1 &&\n idxs[[1]]@value@mode == \"logical\" &&\n idxs[[1]]@value@rank == var@value@rank) {\n mask <- idxs[[1]]\n if (hoist_mask(mask))\n return(var)\n return(Fortran(glue(\"pack({var}, {mask})\"), Variable(var@value@mode, dims = NA)))\n }\n\n if (length(idxs) != var@value@rank)\n stop(\"number of args to x[...] must match the rank of x, received:\",\n deparse1(as.call(c(quote(`[`,args )))))\n\n drop <- args$drop %||% TRUE\n\n idxs <- lapply(idxs, function(subscript) {\n # if (!idx@value@rank %in% 0:1)\n # stop(\"all args to x[...] must have rank 0 or 1\",\n # deparse1(as.call(c(quote(`[`,args )))))\n switch(\n paste0(subscript@value@mode, subscript@value@rank),\n logical0 = {\n Fortran(\":\", Variable(\"integer\", NA))\n },\n logical1 = {\n # we convert to a temp integer vector, doing the equivalent of R's which()\n i <- scope@get_unique_var(\"integer\")\n f <- glue(\"pack([({i}, {i}=1, size({subscript}))], {subscript})\")\n return(Fortran(f, Variable(\"int\", NA)))\n },\n integer0 = {\n if (drop)\n subscript\n else\n Fortran(glue(\"{subscript}:{subscript}\"), Variable(\"int\", 1))\n },\n integer1 = {\n subscript\n },\n # double0 = { },\n # double1 = { },\n stop(\n \"all args to x[...] must be logical or integer of rank 0 or 1\",\n deparse1(as.call(c(quote(`[`, args ))))\n )\n )\n })\n\n dims <- drop_nulls(lapply(idxs, \\(idx) idx@value@dims[[1]]))\n outval <- Variable(var@value@mode, dims)\n Fortran(glue(\"{var}({str_flatten_commas(idxs)})\"), outval)\n\n}\n\n\nr2f_handlers[[\":\"]] <- function(args, scope, ...) {\n # depending on context, this translation can vary.\n\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n args <- whole_doubles_to_ints(args)\n .[start, end] <- lapply(args, r2f, scope, ...)\n step <- glue(\"sign(1, {end}-{start})\")\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{start}:{end}:{step}\"),\n \"for\" = glue(\"{start}, {end}, {step}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {start}, {end}, {step}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\nr2f_handlers[[\"seq\"]] <- function(args, scope, ...) {\n args <- whole_doubles_to_ints(args) # only casts if trunc(dbl) == dbl\n if (!is.null(args$length.out) || !is.null(args$along.with)) {\n stop(\"seq(length.out=, along.with=) not implemented yet\")\n }\n\n\n .[from, to, by] <- lapply(args, r2f, scope, ...)[c(\"from\", \"to\", \"by\")]\n by <- by %||% Fortran(glue(\"sign(1, {to}-{from})\"), Variable(\"integer\"))\n\n # Fortran only supports integer sequences in do and implicit do contexts.\n # to make a double sequence, needs to be in via an implied map() call, like\n # seq(1, 10, .1) -> [(x * 0.1, x = 10, 50)]\n #\n # e.g., i <- scope@get_unique_var(\"integer\")\n # glue(\"[({i} * by, {i} = int(from/by), int(to/by))]\")\n if (from@value@mode != \"integer\" ||\n to@value@mode != \"integer\" ||\n by@value@mode != \"integer\")\n stop(\"non-integer seq()'s not implemented yet.\")\n\n # depending on context, this translation can vary.\n #\n # x[a:b] becomes x(a:b)\n # for(i in a:b){} becomes do i = a,b ...\n # c(a:b) becomes ({tmp}, {tmp}=a,b)\n val <- Variable(\"integer\", NA)\n fr <- switch(\n list(...)$calls |> drop_last() |> last(),\n \"[\" = glue(\"{from}:{to}:{by}\"),\n \"for\" = glue(\"{from}, {to}, {by}\"),\n {\n i <- scope@get_unique_var(\"integer\")\n glue(\"[ ({i}, {i} = {from}, {to}, {by}) ]\")\n }\n # default\n )\n Fortran(fr, val)\n}\n\n\n\n\nr2f_handlers[[\"ifelse\"]] <- function(args, scope, ...) {\n .[mask, tsource, fsource] <- lapply(args, r2f, scope, ...)\n # (tsource, fsource, mask)\n mode <- tsource@value@mode\n dims <- conform(mask@value, tsource@value, fsource@value)@dims\n Fortran(glue(\"merge({tsource}, {fsource}, {mask})\"),\n Variable(mode, dims))\n}\n\n\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- pure elemental unary math intrinsics ----\n\n## real and complex intrinsics\nr2f_handlers[[\"sin\"]] <-\nr2f_handlers[[\"cos\"]] <-\nr2f_handlers[[\"tan\"]] <-\nr2f_handlers[[\"asin\"]] <-\nr2f_handlers[[\"acos\"]] <-\nr2f_handlers[[\"atan\"]] <-\nr2f_handlers[[\"sqrt\"]] <-\nr2f_handlers[[\"exp\"]] <-\nr2f_handlers[[\"log\"]] <-\nr2f_handlers[[\"floor\"]] <-\nr2f_handlers[[\"ceiling\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n intrinsic <- last(list(...)$calls)\n Fortran(glue(\"{intrinsic}({arg})\"), arg@value)\n}\n\nr2f_handlers[[\"log10\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n f <- if(arg@value@mode == \"complex\") {\n glue(\"(log({arg}) / log(10.0_c_double))\")\n } else {\n glue(\"log10({arg})\")\n }\n Fortran(f, arg@value)\n}\n\n## accepts real, integer, or complex\nr2f_handlers[[\"abs\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n if(arg@value@mode == \"complex\")\n arg@value@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), arg@value)\n}\n\n\n# ---- complex elemental unary intrinsics ----\n\nr2f_handlers[[\"Re\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"real({arg})\"), val)\n}\n\nr2f_handlers[[\"Im\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"aimag({arg})\"), val)\n}\n\n# Modulus (magnitude)\nr2f_handlers[[\"Mod\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"abs({arg})\"), val)\n}\n\n# Argument (phase angle, radians)\nr2f_handlers[[\"Arg\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"double\"\n Fortran(glue(\"atan2(aimag({arg}), real({arg}))\"), val)\n}\n\n# conjg() returns a complex value; R uses Conj()\nr2f_handlers[[\"Conj\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n arg <- r2f(args[[1]], scope, ...)\n val <- arg@value\n val@mode <- \"complex\"\n Fortran(glue(\"conjg({arg})\"), val)\n}\n\n\n\n# ---- elemental binary infix operators ----\n\nr2f_handlers[[\"+\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} + {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"-\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} - {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"*\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} * {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"/\"]] <- function(args, scope = NULL, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} / {right})\"), conform(left@value, right@value))\n}\n\nr2f_handlers[[\"^\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n Fortran(glue(\"({left} ** {right})\"), conform(left@value, right@value))\n}\n\n\nr2f_handlers[[\">=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} >= {right})\"), var)\n}\nr2f_handlers[[\">\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} > {right})\"), var)\n}\nr2f_handlers[[\"<\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} < {right})\"), var)\n}\nr2f_handlers[[\"<=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} <= {right})\"), var)\n}\nr2f_handlers[[\"==\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} == {right})\"), var)\n}\nr2f_handlers[[\"!=\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n var <- conform(left@value, right@value)\n var@mode <- \"logical\"\n Fortran(glue(\"({left} /= {right})\"), var)\n}\n\n\n\n# ---- remainder (%%) and integer division (%/%) ----\n#\n# R semantics:\n# x %% y == r where r has the sign of y (divisor)\n# x %/% y == q where q = floor(x / y)\n# and x == r + y * q (within rounding error)\n#\n# Fortran intrinsics:\n# - MODULO(a,p) : remainder with sign(p)\n# - FLOOR(x) : greatest integer ≤ x (real)\n# - AINT(x) : truncation toward 0 (real)\n\nr2f_handlers[[\"%%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n # MODULO gives result with sign(right) – matches R %% behaviour\n Fortran(glue(\"modulo({left}, {right})\"), out_val)\n}\n\nr2f_handlers[[\"%/%\"]] <- function(args, scope, ...) {\n .[left, right] <- lapply(args, r2f, scope, ...)\n out_val <- conform(left@value, right@value)\n\n expr <- switch(\n out_val@mode,\n integer = glue(\"int(floor(real({left}) / real({right})))\"),\n double = glue(\"floor({left} / {right})\"),\n stop(\"%/% only implemented for numeric types\")\n )\n\n Fortran(expr, out_val)\n}\n\n\n\n# TODO: the scalar || probably need some more type checking.\n# TODO: gfortran supports implicit casting that of logical to integer when\n# assigning a logical to a variable declared integer, converting `.true.` to `1`,\n# but this is not a standard language feature, and Intel's `ifort` uses `-1` for `.true`.\n# We should explicitly use\n# `merge(1_c_int, 0_c_int, <lgl>)` to cast logical to int.\nr2f_handlers[[\"&\"]] <-\nr2f_handlers[[\"&&\"]] <-\nr2f_handlers[[\"|\"]] <-\nr2f_handlers[[\"||\"]] <-\nfunction(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n args <- lapply(args, function(a) {\n if (a@value@mode != \"logical\") {\n stop(\"must be logical\")\n }\n a\n })\n .[left, right] <- args\n\n operator <- switch(last(list(...)$calls),\n `&` = , `&&` = \".and.\",\n `|` = , `||` = \".or.\")\n\n s <- glue(\"{left} {operator} {right}\")\n val <- conform(left@value, right@value)\n val@mode <- \"logical\"\n Fortran(s, val)\n}\n\n\n\n\n# --- constructors ----\n\n\nr2f_handlers[[\"c\"]] <- function(args, scope = NULL, ...) {\n ff <- lapply(args, r2f, scope, ...)\n s <- glue(\"[ {str_flatten_commas(ff)} ]\")\n lens <- lapply(ff[order(map_int(ff, \\(f) f@value@rank))], function(e) {\n rank <- e@value@rank\n if (rank == 0)\n 1L\n else if (rank == 1)\n e@value@dims[[1]]\n else\n stop(\"all args passed to c() must be scalars or 1-d arrays\")\n })\n mode <- reduce_promoted_mode(ff)\n len <- Reduce(\\(l1, l2) {\n if (is_scalar_na(l1) || is_scalar_na(l2)) {\n NA\n } else if (is_wholenumber(l1) && is_wholenumber(l2)) {\n l1 + l2\n } else {\n call(\"+\", l1, l2)\n }\n }, lens)\n Fortran(s, Variable(mode, list(len)))\n}\n\n\nr2f_handlers[[\"cbind\"]] <- function(e, scope) {\n .NotYetImplemented()\n ee <- lapply(e[-1], r2f, scope)\n ncols <- lapply(ee, function(f) {\n if (f@value@rank %in% c(0, 1))\n 1\n else if (f@value@rank == 2)\n f@value@dims[[2]]\n })\n ncols <- Reduce(\\(a, b) call(\"+\", a, b), ncols)\n ncols <- eval(ncols, scope@sizes)\n}\n\n\n\nr2f_handlers[[\"<-\"]] <- function(args, scope, ...) {\n target <- args[[1]]\n if (is.call(target)) {\n # given a call like `foo(x) <- y`, dispatch to `foo<-`\n target_callable <- target[[1]]\n stopifnot(is.symbol(target_callable))\n name <- as.symbol(paste0(as.character(target_callable), \"<-\"))\n handler <- get_r2f_handler(name)\n return(handler(args, scope, ...)) # new hoist target\n }\n\n # It sure seems like it's be nice if the Fortran() constructor\n # took mode and dims as args directly,\n # without needing to go through Variable...\n stopifnot(is.symbol(target))\n name <- as.character(target)\n\n value <- args[[2]]\n value <- r2f(value, scope, ...)\n\n # immutable / copy-on-modify usage of Variable()\n if (is.null(var <- get0(name, scope))) {\n # this is a binding to a new symbol\n var <- value@value\n var@name <- name\n scope[[name]] <- var\n\n } else {\n # The var already exists, this assignment is a modification / reassignment\n check_assignment_compatible(var, value@value)\n var@modified <- TRUE\n # could probably drop this @modified property, and instead track\n # if the var populated by declare is identical at the end (e.g., perhaps by\n # address, or by attaching a unique id to each var, or ???)\n assign(name, var, scope)\n }\n\n Fortran(glue(\"{name} = {value}\"))\n}\n\n\nr2f_handlers[[\"[<-\"]] <- function(args, scope = NULL, ...) {\n\n # TODO: handle logical subsetting here, which must become a where a construct like:\n # x[lgl] <- val\n # becomes\n # where (lgl)\n # x = val\n # end where\n # ! but if {va} references {x}, it will only see the subset x, not the full {x}\n # e.g.,\n # sum(x) is not the same as `where lgl \\n sum(x) \\n end where`\n # ditto for ifelse() ?\n # e <- as.list(e)\n\n stopifnot(is_call(target <- args[[1L]], \"[\"))\n target <- r2f(target, scope)\n\n value <- r2f(args[[2L]], scope)\n Fortran(glue(\"{target} = {value}\"))\n}\n\nreduce_promoted_mode <- function(...) {\n\n getmode <- function(d) {\n if (inherits(d, Fortran))\n d <- d@value\n if (inherits(d, Variable))\n return(d@mode)\n if (is.list(d) && length(d))\n lapply(d, getmode)\n }\n modes <- unique(unlist(getmode(list(...))))\n\n if (\"double\" %in% modes)\n \"double\"\n else if (\"integer\" %in% modes)\n \"integer\"\n else if (\"logical\" %in% modes)\n \"logical\"\n else\n NULL\n\n}\n\n\nr2f_handlers[[\"=\"]] <- r2f_handlers[[\"<-\"]]\n\nr2f_handlers[[\"logical\"]] <- function(args, scope, ...) {\n Fortran(\".false.\", Variable(mode = \"logical\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"integer\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"integer\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"double\"]] <- function(args, scope, ...) {\n Fortran(\"0\", Variable(mode = \"double\", dims = r2dims(args, scope)))\n}\n\nr2f_handlers[[\"numeric\"]] <- r2f_handlers[[\"double\"]]\n\nr2f_handlers[[\"character\"]] <- r2f_handlers[[\"raw\"]] <-\n .r2f_handler_not_implemented_yet\n\n\nr2f_handlers[[\"matrix\"]] <- function(args, scope = NULL, ...) {\n\n args$data %||% stop(\"matrix(data=) must be provided, cannot be NA\")\n out <- r2f(args$data, scope, ...)\n out@value@dims <- r2dims(list(args$nrow, args$ncol), scope)\n out\n\n # TODO: reshape() if !passes_as_scalar(out)\n}\n\n\n\nconform <- function(..., mode = NULL) {\n var <- NULL\n # technically, types are implicit promoted, but we'll let <- handle that.\n for (var in drop_nulls(list(...))) {\n if (passes_as_scalar(var)) {\n next\n } else {\n break\n }\n }\n if (is.null(var))\n NULL\n else\n Variable(mode %||% var@mode, var@dims)\n }\n\n\n\n# ---- printers ----\n\n\nr2f_handlers[[\"cat\"]] <- function(args, scope, ...) {\n args <- lapply(args, r2f, scope, ...)\n # can do a lot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"character\")\n label <- args[[1]]\n if (!endsWith(label, \"\\n\"))\n stop(\"cat(<strings>) must end with '\\n'\")\n label <- substring(label, 1, nchar(label)-1)\n\n Fortran(glue('call labelpr(\"{label}\", {nchar(label)})'))\n}\n\nr2f_handlers[[\"print\"]] <- function(args, scope = NULL, ...) {\n # args <- lapply(as.list(e)[-1], r2f, scope)\n # args <- as.list(e)[-1]\n # can do alot more here still, just a POC for now\n stopifnot(length(args) == 1, typeof(args[[1]]) == \"symbol\")\n name <- args[[1]]\n var <- get(name, envir = scope)\n name <- as.character(name)\n if (var@mode == \"logical\")\n name <- sprintf(\"(%s/=0)\", name)\n label <- \"\"\n # browser()\n if (passes_as_scalar(var)) {\n # } \"scalar\"\n # paste0(c(var@mode, scalar) collapse = \"_\"),\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr1\",\n double = \"dblepr1\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name})'))\n } else {\n printer <- switch(\n var@mode,\n logical = ,\n integer = \"intpr\",\n double = \"dblepr\",\n {print(var); stop(\"Unsupported type in print()\")}\n )\n\n Fortran(glue('call {printer}(\"{label}\", {nchar(label)}, {name}, size({name}))'))\n }\n}\n\n# r2f_handlers[[\"ifelse\"]] <- function(e, scope) {\n# # TODO:\n# # <- and [<- need to be aware of this construct for it to make sense.\n# .[test, yes, no] <- lapply(e[-1], r2f, scope)\n# Fortran(glue(\"where ({test}}\n# {indent(yes)}\n# elsewhere\n# {indent({no})\n# end where\"))\n# }\n\n\nr2f_handlers[[\"length\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x})\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"nrow\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 1)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"ncol\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"size({x}, 2)\"), Variable(\"integer\"))\n}\nr2f_handlers[[\"dim\"]] <- function(args, scope, ...) {\n x <- r2f(args[[1]], scope, ...)\n Fortran(glue(\"shape({x})\"), Variable(\"integer\", x@value@rank))\n}\n\n\n\n\n# this is just `[` handler\nr2f_slice <- function(args, scope, ...) { }\n\n\n\n# ---- control flow ----\n\n\nr2f_handlers[[\"if\"]] <- function(args, scope, ..., hoist = NULL) {\n # cond uses the current hoist context.\n cond <- r2f(args[[1]], scope, ..., hoist = hoist)\n\n # true and false branchs gets their own hoist target.\n true <- r2f(args[[2]], scope, ..., hoist = NULL)\n\n if (length(args) == 2) {\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n end if\n \"))\n } else {\n false <- r2f(args[[3]], scope, ..., hoist = NULL)\n Fortran(glue(\"\n if ({cond}) then\n {indent(true)}\n else\n {indent(false)}\n end if\n \"))\n }\n}\n\n\n# TODO: return\n\n# ---- repeat ----\nr2f_handlers[[\"repeat\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 1L)\n body <- r2f(args[[1]], scope, ...)\n Fortran(glue(\n \"do\n {indent(body)}\n end do\n \"))\n}\n\n# ---- break ----\nr2f_handlers[[\"break\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"exit\")\n}\n\n# ---- break ----\nr2f_handlers[[\"next\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 0L)\n Fortran(\"cycle\")\n}\n\n# ---- while ----\nr2f_handlers[[\"while\"]] <- function(args, scope, ...) {\n stopifnot(length(args) == 2L)\n cond <- r2f(args[[1]], scope, ...)\n body <- r2f(args[[2]], scope, ...) ## should we set a new hoist target here?\n Fortran(glue(\n \"do while ({cond})\n {indent(body)}\n end do\n \"))\n}\n\n## ---- for ----\nr2f_iterable <- function(e, scope, ...) {\n .NotYetImplemented()\n\n if (is.symbol(e)) {\n var <- get(e, scope)\n iterable <- r2f(...)\n }\n\n # list(var, iterable, body_prefix)\n}\n\n\n\n\nr2f_handlers[[\"for\"]] <- function(args, scope, ...) {\n .[var, iterable, body] <- args\n stopifnot(is.symbol(var))\n var <- as.character(var)\n scope[[var]] <- Variable(mode = \"integer\", name = var)\n\n iterable <- r2f_iterable_handlers[[as.character(iterable[[1]])]](iterable, scope)\n body <- r2f(body, scope, ...)\n\n Fortran(glue(\n \"do {var} = {iterable}\n {indent(body)}\n end do\n \"))\n}\n\nr2f_iterable_handlers := new.env()\n\nr2f_iterable_handlers[[\"seq_len\"]] <- function(e, scope, ...) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_len()\")\n x <- x[[1]]\n start <- 1L\n end <- r2f(x)\n glue(\"{start}, {end}\")\n}\n\nr2f_iterable_handlers[[\"seq\"]] <- function(e, scope) {\n\n ee <- match.call(seq.default, e)\n ee <- whole_doubles_to_ints(ee)\n\n start <- r2f(ee$from, scope)\n end <- r2f(ee$to, scope)\n step <- if (is.null(ee$by))\n glue(\"sign(1, {end}-{start})\")\n else\n r2f(ee$by, scope)\n\n str_flatten_commas(\n start, end, step\n )\n}\n\nr2f_iterable_handlers[[\":\"]] <- function(e, scope) {\n\n ee <- whole_doubles_to_ints(e)\n .[start, end] <- as.list(ee)[-1] |> lapply(r2f, scope)\n\n glue(\"{start}, {end}, sign(1, {end}-{start})\")\n}\n\n\n\nr2f_iterable_handlers[[\"seq_along\"]] <- function(e, scope) {\n x <- as.list(e)[-1]\n if (length(x) != 1) stop(\"too many args to seq_along()\")\n x <- x[[1]]\n start <- 1\n end <- sprintf(\"size(%s)\", r2f(x, scope))\n glue(\"{start}, {end}\")\n}\n\n\n# ---- helpers ----\n\ncheck_call <- function(e, nargs) {\n if (length(e) != (nargs+1L))\n stop(\"Too many args to: \", as.character(e[[1L]]))\n}\n"], ["/quickr/R/quick.R", "#' Compile a Quick Function\n#'\n#' Compile an R function.\n#'\n#' @param fun An R function\n#' @param name Optional string, name to use for the function.\n#'\n#' @details\n#'\n#' ## `declare(type())` syntax:\n#'\n#' The shape and mode of all function arguments must be declared. Local and\n#' return variables may optionally also be declared.\n#'\n#' `declare(type())` also has support for declaring size constraints, or size\n#' relationships between variables. Here are some examples of declare calls:\n#'\n#' ```r\n#' declare(type(x = double(NA))) # x is a 1-d double vector of any length\n#' declare(type(x = double(10))) # x is a 1-d double vector of length 10\n#' declare(type(x = double(1))) # x is a scalar double\n#'\n#' declare(type(x = integer(2, 3))) # x is a 2-d integer matrix with dim (2, 3)\n#' declare(type(x = integer(NA, 3))) # x is a 2-d integer matrix with dim (<any>, 3)\n#'\n#' # x is a 4-d logical matrix with dim (<any>, 24, 24, 3)\n#' declare(type(x = logical(NA, 24, 24, 3)))\n#'\n#' # x and y are 1-d double vectors of any length\n#' declare(type(x = double(NA)),\n#' type(y = double(NA)))\n#'\n#' # x and y are 1-d double vectors of the same length\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' # x and y are 1-d double vectors, where length(y) == length(x) + 2\n#' declare(type(x = double(n)),\n#' type(y = double(n+2)))\n#' ```\n#'\n#' You can provide declarations to `declare()` as:\n#'\n#' - Multiple arguments to a single `declare()` call\n#' - Separate `declare()` calls\n#' - Multiple arguments within a code block (`{}`) inside `declare()`\n#'\n#' ```r\n#' declare(\n#' type(x = double(n)),\n#' type(y = double(n)),\n#' )\n#'\n#' declare(type(x = double(n)))\n#' declare(type(y = double(n)))\n#'\n#' declare({\n#' type(x = double(n))\n#' type(y = double(n))\n#' })\n#' ```\n#'\n#' ## Return values\n#'\n#' The shape and type of a function return value must be known at compile time.\n#' In most situations, this will be automatically inferred by `quick()`. However,\n#' if the output is dynamic, then you may need to provide a hint.\n#' For example, returning the result of `seq()` will fail because the output shape\n#' cannot be inferred.\n#'\n#' ```r\n#' # Will fail to compile:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' ```\n#'\n#' However, if the output size can be declared as a dynamic expression using other\n#' values known at runtime, compilation will succeed:\n#'\n#' ```r\n#' # Succeeds:\n#' quick_seq <- quick(function(start, end) {\n#' declare({\n#' type(start = integer(1))\n#' type(end = integer(1))\n#' type(out = integer(end - start + 1))\n#' })\n#' out <- seq(start, end)\n#' out\n#' })\n#' quick_seq(1L, 5L)\n#' ```\n#'\n#' @returns A quicker R function.\n#' @export\n#' @examples\n#' add_ab <- quick(function(a, b) {\n#' declare(type(a = double(n)),\n#' type(b = double(n)))\n#' out <- a + b\n#' out\n#' })\n#' add_ab(1, 2)\nquick <- function(fun, name = NULL) {\n if (is.null(name)) {\n name <- if (is.symbol(substitute(fun)))\n deparse(substitute(fun))\n else\n make_unique_name(prefix = \"anonymous_quick_function_\")\n }\n\n if (nzchar(pkgname <- Sys.getenv(\"DEVTOOLS_LOAD\"))) {\n if (!collector$is_active()) {\n if (!requireNamespace(\"pkgload\", quietly = TRUE)) {\n stop(\"Please install 'pkgload'\")\n }\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_code)) {\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n defer(dump_collected(), sys.frame(i), after = TRUE)\n break\n }\n }\n }\n }\n\n if (collector$is_active()) {\n # we are in a quickr::compile_package() or a devtools::load_all() call,\n # merely collecting functions at this point.\n quick_closure <- create_quick_closure(name, fun)\n collector$add(name = name, closure = fun, quick_closure = quick_closure)\n return(quick_closure)\n }\n\n pkgname <- parent.pkg()\n if (!is.null(pkgname) && pkgname != \"quickr\") {\n # we are in a package - but outside a quickr::compile_package() call.\n return(create_quick_closure(name, fun))\n }\n\n # not in a package. Compile and load eagerly.\n attr(fun, \"name\") <- name\n fun <- compile(r2f(fun))\n attr(fun, \"name\") <- NULL\n\n fun\n}\n\ncompile <- function(fsub, build_dir = tempfile(paste0(fsub@name, \"-build-\"))) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n name <- fsub@name\n c_wrapper <- make_c_bridge(fsub)\n\n if (dir.exists(build_dir)) unlink(build_dir, recursive = T)\n if (!dir.exists(build_dir))\n dir.create(build_dir)\n owd <- setwd(build_dir)\n on.exit(setwd(owd))\n\n fsub_path <- paste0(name, \"_fsub.f90\")\n c_wrapper_path <- paste0(name, \"_c_wrapper.c\")\n dll_path <- paste0(name, .Platform$dynlib.ext)\n writeLines(fsub, fsub_path)\n writeLines(c_wrapper, c_wrapper_path)\n\n suppressWarnings({\n result <- system2(\n R.home(\"bin/R\"),\n c(\"CMD SHLIB --use-LTO\", \"-o\", dll_path, fsub_path, c_wrapper_path),\n stdout = TRUE, stderr = TRUE\n )\n })\n if (!is.null(attr(result, \"status\"))) {\n writeLines(result, stderr())\n str(attributes(result))\n stop(\"Compilation Error\")\n }\n\n # tryCatch(dyn.unload(dll_path), error = identity)\n dll <- dyn.load(dll_path)\n c_wrapper_name <- paste0(fsub@name, \"_\")\n ptr <- getNativeSymbolInfo(c_wrapper_name, dll)$address\n\n create_quick_closure(fsub@name, fsub@closure, native_symbol = ptr)\n}\n\n\n\ncreate_quick_closure <- function(name, closure,\n native_symbol = as.name(paste0(name, \"_\"))) {\n body(closure) <- as.call(c(quote(.External), native_symbol,\n lapply(names(formals(closure)), as.name)))\n closure\n}\n\n\n\ncheck_all_var_names_valid <- function(fun) {\n nms <- unique(c(names(formals(fun)), all.vars(body(fun), functions = FALSE)))\n invalid <- endsWith(nms, \"_\") | startsWith(nms, \"_\") | nms %in% c(\n\n # clashes with Fortran subroutine symbols\n \"c_int\", \"c_double\", \"c_ptrdiff_t\",\n\n # clashes with C bridge symbols\n \"int\" #, \"double\",\n\n # ??? (clashes with R symbols?)\n # \"double\", \"integer\"\n )\n if (any(invalid)) {\n stop(\"symbols cannot start or end with '_', but found: \",\n glue_collapse(invalid, \", \", last = \", and \"))\n }\n}\n\n\n\n# ---- utils ----\n\nmake_unique_name <- local({\n i <- 0L\n function(prefix = \"tmp\") {\n paste0(prefix, i <<- i + 1L)\n }\n})\n"], ["/quickr/R/classes.R", "#' @import S7\nNULL\n\nnew_setter <- function(coerce = NULL, coerce_null = FALSE, set_once = FALSE, env = parent.frame(2L)) {\n\n if (is.null(coerce) || isFALSE(coerce) && isFALSE(set_once))\n return()\n\n bind_name <- quote(name <- as.character(last(attr(self, \".setting_prop\", TRUE))))\n\n check_set_once <- if (set_once) {\n quote(if (!is.null(prop(self, name)))\n stop(name, \" can only be set once\"))\n }\n\n rebind_coerced_value <-\n if (is.null(coerce) || isFALSE(coerce)) {\n NULL\n } else if (isTRUE(coerce)) {\n quote(value <- convert(\n from = value,\n to = S7_class(self)@properties[[as.character(name)]]$class\n ))\n } else if (is.function(coerce) || is.symbol(coerce)) {\n bquote(value <- .(coerce)(value))\n } else if (is.language(coerce)) {\n bquote(value <- .(coerce))\n } else {\n stop(\"coerce must be TRUE, FALSE, NULL, a function, a symbol, or a call\")\n }\n\n if (!coerce_null && !is.null(rebind_coerced_value)) {\n rebind_coerced_value <- bquote(if (!is.null(value)) .(rebind_coerced_value))\n }\n\n set <- quote(`prop<-`(\n object = self,\n name = name,\n check = FALSE,\n value = value\n ))\n\n new_function(\n args = alist(self = , value = ),\n body = as.call(c(quote(`{`),\n bind_name,\n check_set_once,\n rebind_coerced_value,\n set)),\n env = env\n )\n}\n\n\nnew_scalar_validator <- function(allow_null = FALSE,\n allow_na = FALSE,\n additional_checks = NULL,\n env = parent.frame(2L)) {\n checks <- c(\n if (allow_null) quote(if (is.null(value)) return()),\n quote(if (length(value) != 1L) return(\"must be a scalar\")),\n if (!allow_na) quote(if (anyNA(value)) return(\"must not be NA\")),\n additional_checks\n )\n\n new_function(\n args = alist(value = ),\n body = as.call(c(quote(`{`), checks)),\n env = parent.frame(2L)\n )\n}\n\n\nprop_bool <- function(default, allow_null = FALSE, allow_na = FALSE, set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n new_property(\n class = if (allow_null) NULL | class_logical else class_logical,\n setter = new_setter(set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null,\n allow_na = allow_na),\n default = default\n )\n}\n\n\nprop_string <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = FALSE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(as.character)\n\n new_property(\n class = if (allow_null) NULL | class_character else class_character,\n default = default,\n validator = new_scalar_validator(allow_null = allow_null),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once)\n )\n}\n\n\nprop_wholenumber <- function(default = NULL,\n allow_null = FALSE,\n allow_na = FALSE,\n coerce = TRUE,\n set_once = FALSE) {\n stopifnot(is_bool(set_once), is_bool(allow_null), is_bool(allow_na))\n\n if (isTRUE(coerce))\n coerce <- quote(\n if (is_wholenumber(value)) as.integer(value)\n else stop(\"@\", name, \" must be a whole number, but received: \", value)\n )\n\n new_property(\n class = if (allow_null) NULL | class_integer else class_integer,\n default = as.integer(default),\n setter = new_setter(coerce = coerce,\n coerce_null = !allow_null,\n set_once = set_once),\n validator = new_scalar_validator(allow_null = allow_null)\n )\n}\n\n\nprop_enum <- function(values,\n nullable = FALSE,\n default = if (nullable) NULL else values[1],\n exact = FALSE,\n set_once = FALSE) {\n\n stopifnot(\n \"values must be a character vector of length >= 2 without any NA\" =\n is.character(values) && length(values) >= 2 && !anyNA(values)\n )\n\n coerce <- if (exact) NULL else {\n bquote(if (length(value) == 1L && !anyNA(i <- charmatch(value, .(values))))\n .(values)[i] else value)\n }\n\n display_values <- glue_collapse(single_quote(values), sep = \", \", last = \", or \")\n msg <- sprintf(\"must be either %s, not '\", display_values)\n validator <- new_scalar_validator(allow_null = nullable,\n additional_checks = bquote(\n if (!match(value, .(values), nomatch = 0L))\n return(paste0(.(msg), value, \"'.\"))\n ))\n\n new_property(\n class = if (nullable) NULL | class_character else class_character,\n setter = new_setter(coerce = coerce, coerce_null = !nullable, set_once = set_once),\n validator = validator,\n default = default\n )\n}\n\n\n.atomic_type_names <- c(\"integer\", \"logical\", \"double\",\n \"character\", \"raw\", \"complex\")\n\n\n# the print method for this should only print non-null values\nVariable := new_class(\n properties = list(\n\n mode = prop_enum(.atomic_type_names, nullable = TRUE, set_once = FALSE),\n\n dims = new_property(\n # NULL means scalar\n NULL | class_list,\n setter = function(self, value) {\n if (!length(value))\n return(self)\n\n value <- switch(typeof(value),\n logical = , integer = , double = as.list(value),\n language = , symbol = list(value), # implicit rank-1\n list = value,\n stop(\"@dims must be a list\")\n )\n\n value <- lapply(value, \\(axis) {\n if (is.language(axis)) {\n axis\n } else if (is_wholenumber(axis) || is_scalar_na(axis)) {\n as.integer(axis)\n } else {\n stop(sprintf(\n \"%s@dims must be a list of language or scalar integers, not %s\",\n self@name %||% '', axis\n ))\n }\n })\n\n self@dims <- value\n self\n } # dims$setter\n ), # dims = new_property()\n\n name = prop_string(\n allow_null = TRUE,\n coerce = quote(switch(typeof(value), symbol = as.character(value), value)),\n set_once = FALSE #TRUE\n ),\n\n rank = new_property(\n class_integer,\n getter = function(self) {\n length(self@dims)\n }),\n\n modified = prop_bool(default = FALSE),\n\n r = new_property(\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n # custom setter to workaround https://github.com/RConsortium/S7/issues/511\n attr(self, \"r\") <- value\n self\n }\n ),\n\n is_arg = prop_bool(default = FALSE),\n\n is_return = prop_bool(default = FALSE),\n\n # TRUE for closure args and return values, FALSE for all other vars.\n is_external = new_property(\n class_logical,\n getter = function(self)\n self@is_arg || self@is_return\n ),\n\n is_scalar = new_property(\n class_logical,\n getter = function(self) {\n self@rank == 0 || identical(self@dims, list(1L))\n }\n )\n\n )\n)\n\n# method(print, Variable) <- function(x, ...) {\n#\n# }\n\n\n\nFortran := new_class(\n class_character,\n\n properties = list(\n\n value = NULL | Variable,\n\n r = new_property(\n # custom setter only to workaround https://github.com/RConsortium/S7/issues/511\n NULL | class_language | class_atomic,\n setter = function(self, value) {\n attr(self, \"r\") <- value\n self\n }\n )\n ),\n\n validator = function(self) {\n if (length(self) != 1L)\n \"must be a length 1 string\"\n }\n)\n\n\nFortranSubroutine := new_class(Fortran, properties = list(\n name = prop_string(),\n signature = class_character,\n closure = class_function,\n scope = NULL | class_environment,\n c_bridge = S7::new_property(\n NULL | class_character,\n getter = function(self) {\n make_c_bridge(self) %error% NULL\n })\n))\n\n`%error%` <- function(x, y) tryCatch(x, error = function(e) y)\n\ntry_prop <- function(object, name) S7::prop(object, name) %error% NULL\n\nemit <- function(..., sep = \"\", end = \"\\n\") cat(..., end, sep = sep)\n\nmethod(format, Variable) <- function(x, ...) {\n capture.output(str(x))\n}\n\nmethod(as.character, Variable) <- function(x, ...)\n x@name %||% stop(\"Variable does not have a name\")\n\nmethod(print, Fortran) <- function(x, ...) {\n emit(trimws(x), end = \"\\n\\n\")\n for(prop_name in c(\"value\", \"r\", \"c_bridge\"))\n if (!is.null(prop_val <- try_prop(x, prop_name))) {\n emit(\"@\", prop_name, \": \", trimws(indent(format(prop_val))));\n }\n}\n"], ["/quickr/R/manifest.R", "\n\n\n### local variables with unspecified size are 'allocatable'. If they are bound\n### to a named symbol, the manifest must mark it as allocatable.\n###\n### Generally, if an expression produces an array of unspecified size, even if\n### it's never bound, it's still 'allocatable'. For example, an inline fortran\n### `pack()` call likely still produces a corresponding `malloc()` in the\n### generated code, regardless of if the output of `pack()` is bound to\n### a symbol (in the case of pack specifically, the malloc is behind a\n### _gfortran_pack() call.\n###\n### We can potentially link/mask `_malloc` and `_free` with a custom one that\n### uses R_alloc(), which will automatically free after the .External() call\n### returns. We can also pass along -fstack-arrays to gfortran and flang-new\n### (llvm), and that will mostly get rid most of the malloc calls, instead\n### allocating arrays on the C stack (which will automatically free on\n### return/lngjmp), but that will run into issues with larger arrays (especially\n### on windows)\n###\n### local vars of undefined sizes are allocatable. These will typically be\n### allocated on the c stack if they are not too large, but may include a\n### malloc+free call if they are large. Those might leak if we lngjmp\n### away (e.g., due to an interrupt). This potential leak is a non-issue for\n### now, since interrupts aren't supported yet, so there is no risk of lngjmp.\n###\n### When we do add support for interruptable quick functions, this potential\n### leak could be guarded against by:\n###\n### a) linking malloc -> R_alloc() for the fortran compilation unit which\n### would make the memory automatically be released after .External()\n### return. Note that unlinke malloc(), R_alloc() is not thread safe, so we would need\n### additional work for a `do concurrent` context to be supported.\n###\n### b) forcing all arrays to be stack allocated with -fstack-arrays passed\n### to the gfortran/flang-new. This is not a great, since c stack limits are\n### typically \"small\" and enforced by the OS.\n\nr2f.scope <- function(scope) {\n\n vars <- as.list.environment(scope, all.names = TRUE)\n vars <- lapply(vars, function(var) {\n\n intent_in <- var@name %in% names(formals(scope@closure))\n intent_out <- var@name == closure_return_var_name(scope@closure) || intent_in && var@modified\n\n intent <-\n if (intent_in && intent_out) \"intent(in out)\"\n else if (intent_in) \"intent(in)\"\n else if (intent_out) \"intent(out)\"\n else NULL\n\n type <- switch(var@mode,\n double = \"real(c_double)\",\n integer = \"integer(c_int)\",\n complex = \"complex(c_double_complex)\",\n logical = if (intent_in || intent_out) \"integer(c_int)\" else \"logical\",\n raw = \"integer(c_int8_t)\",\n stop(\"unrecognized kind: \", format(var))\n )\n\n dims <- if (passes_as_scalar(var)) {\n NULL\n } else {\n dims2f(var@dims, scope) |> str_flatten_commas() |> sprintf(fmt = \"(%s)\")\n }\n\n allocatable <- if (!is.null(dims) && grepl(\":\", dims, fixed = TRUE))\n \"allocatable\"\n\n if (intent_in && intent_out && !is.null(allocatable))\n stop(\"all input and output vars must have a fully defined shape\")\n\n name <- var@name\n comment <- if (var@mode == \"logical\") \" ! logical\"\n\n glue('{str_flatten_commas(type, intent, allocatable)} :: {name}{dims}{comment}',\n .null = \"\")\n })\n\n # vars that will be visible in the C bridge, either as an input or output\n non_local_var_names <- unique(c(names(formals(scope@closure)),\n closure_return_var_name(scope@closure)))\n\n # collect all size_names; sort so non-locals are declared first.\n size_names <- unique(unlist(lapply(non_local_var_names, function(name) {\n var <- scope[[name]]\n lapply(var@dims, all.names, functions = FALSE, unique = TRUE)\n }))) |> setdiff(names(formals(scope@closure)))\n\n sizes <- lapply(size_names, function(name) {\n kind <- if (endsWith(name, \"_len_\")) \"c_ptrdiff_t\" else \"c_int\"\n glue(\"integer({kind}), intent(in), value :: {name}\")\n })\n\n manifest <- compact(list(\n sizes = sizes,\n args = vars[non_local_var_names],\n locals = vars[setdiff(names(vars), non_local_var_names)]\n ))\n\n manifest <- imap(manifest, \\(declarations, category)\n str_flatten_lines(paste(\"!\", category), declarations)) |>\n str_flatten(\"\\n\\n\")\n\n manifest <- str_flatten_lines(\"! manifest start\", manifest, \"! manifest end\")\n\n # symbols that must come in as args to the subroutine\n # # method=\"radix\" for locale-independent stable order.\n signature <- unique(c(non_local_var_names, sort(size_names, method = \"radix\")))\n attr(manifest, \"signature\") <- signature\n\n manifest\n}\n\n\n\n## fortran precedence order\n## ** (exp)\n## * /\n## + -\n##\n## R prededence order\n## ^\n## - +\n## %/% %%\n## * /\n\n## generally, we just deparse() to convert an axis size.\n## except for NA, which becomes \":\"\n\ndims2f_eval_base_env <- new.env(parent = emptyenv())\ndims2f_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\n\n# any call always evaluates to a string.\n# every argument will be either:\n# - NA -> translates to \":\"\n# - a symbol -> translates to deparsed string\n# - a call ->\n\ndims2f_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2f_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2f_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2f_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"real({e1}) / real({e2})\")\n# dividing integers truncates towards 0\ndims2f_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"int({e1}) / int({e2})\")\ndims2f_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"mod(int({e1}), int({e2}))\")\ndims2f_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1})**({e2})\")\n\n\ndims2f <- function(dims, scope) {\n syms <- unique(unlist(lapply(dims, \\(d) if (is.language(d)) all.vars(d))))\n vars <- as.list(syms)\n names(vars) <- syms\n eval_env <- list2env(vars, parent = dims2f_eval_base_env)\n dims <- map_chr(dims, function(d) {\n d <- eval(d, eval_env)\n if (is.symbol(d)) as.character(d)\n else if (is_wholenumber(d)) as.character(d)\n else if (is_scalar_na(d)) \":\"\n else if (is_string(d)) d\n else if (inherits(d, Variable)) {\n # a locally allocated var that is a return var\n if (!d@modified && d@is_arg)\n return(d@name)\n stop(\"unexpected axis size value\")\n }\n })\n if (!length(dims) || identical(dims, \"1\")) \"\"\n else str_flatten_commas(dims)\n}\n\n"], ["/quickr/R/compile-package.R", "\n\n\n#' Compile all `quick()` functions in a package.\n#'\n#' This will compile all `quick()` functions in an R package, and\n#' generate source files in the `src/` directory.\n#'\n#' Note, this function is automatically invoked during a `pkgload::load_all()` call.\n#'\n#' @param path Path to an R package\n#'\n#' @returns Called for its side effect.\n#' @export\ncompile_package <- function(path = \".\") {\n if (path != \".\") {\n owd <- setwd(path)\n on.exit(setwd(owd), add = TRUE)\n }\n\n if (!dir.exists(\"R\") || !file.exists(\"DESCRIPTION\"))\n stop(path, \" does not appear to be an R package.\")\n\n pkgname <- read.dcf(\"DESCRIPTION\", \"Package\")\n if (length(pkgname) != 1)\n stop(sprintf(\"path '%s' does not point to an R package\", path))\n pkgname <- as.character(pkgname)\n\n # collect all `quick()` calls in the package\n collector$activate(paste0(pkgname, \":quick_funcs\"))\n\n # TODO: need to unset various R_* env vars, or just\n # take a dep on callr\n system2(file.path(R.home(\"bin\"), \"R\"),\n c(\"-q\", \"-e\", shQuote(\"pkgload::load_all()\")))\n}\n\n\ndump_collected <- function() {\n\n collected <- collector$get_collected()\n\n # try to resolve closure names for anonymous functions\n pkg_ns <- topenv(environment(collected[[1L]]$closure))\n pkg_funcs <- as.list.environment(pkg_ns, all.names = TRUE)\n tab <- hashtab(\"address\", length(collected))\n for (i in seq_along(pkg_funcs)) {\n if (typeof(fn <- pkg_funcs[[i]]) == \"closure\")\n # if is quick closure ...\n sethash(tab, pkg_funcs[[i]], names(pkg_funcs)[i])\n }\n\n quick_funcs <- unlist(recursive = FALSE, lapply(collected, function(x) {\n if (!startsWith(x$name, \"anonymous_quick_function_\"))\n return(setNames(list(x$closure), x$name))\n true_name <- gethash(tab, x$quick_closure)\n if (is.null(true_name))\n return(setNames(list(x$closure), x$name))\n # update pkg_ns with true name\n quick_closure <- create_quick_closure(true_name, x$closure)\n pkg_ns[[true_name]] <- quick_closure\n remhash(tab, x$quick_closure)\n setNames(list(x$closure), true_name)\n }))\n\n\n pkgname <- basename(normalizePath(\".\"))\n\n # check if we have a useDynLib line in NAMESPACE.\n if (!any(sapply(parse(file = \"NAMESPACE\"), function(e) {\n identical(e[[1]], quote(useDynLib)) && isTRUE(e$.registration)\n })))\n message(\"- Please add this roxygen directive somewhere in the Package R sources:\\n \",\n glue(\"#' @useDynLib {pkgname}, .registration = TRUE\"), \"\\n\",\n \"- Then run `devtools::document()`\\n\")\n\n sources <- zip_lists(imap(quick_funcs, function(func, name) {\n fsub <- new_fortran_subroutine(name, func)\n cbridge <- make_c_bridge(fsub, headers = name == names(quick_funcs)[1])\n list(f90 = fsub, c = cbridge)\n })) |> lapply(\\(x) x |> unlist() |> interleave(\"\\n\"))\n\n entries <- paste0(sprintf(' {\"%1$s\", (DL_FUNC) &%1$s, -1}',\n paste0(names(quick_funcs), \"_\")),\n collapse = \",\\n\")\n entries <- sprintf(\"static const R_ExternalMethodDef QuickrEntries[] = {\\n%s\\n};\",\n entries)\n\n append(sources$c) <- c(\"\", entries, \"\")\n\n R_init_pkg <- paste0(\"R_init_\", pkgname, \"(\")\n has_pkg_init_fn <- list.files(\"src\", pattern = \"\\\\.(c|cpp|h|hpp|c\\\\+\\\\+)$\",\n recursive = TRUE, all.files = TRUE,\n full.names = TRUE) |>\n setdiff(\"src/quickr_entrypoints.c\") |>\n lapply(function(f) {\n any(grepl(R_init_pkg, readLines(f, warn = FALSE), fixed = TRUE))\n }) |> unlist() |> any()\n\n append(sources$c) <- c(\"#include <R_ext/Rdynload.h>\", \"\")\n\n init_fn <- if (has_pkg_init_fn) {\n glue(\"\n void R_init_{pkgname}_quick_functions(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n }}\")\n } else {\n init_pkgname <- gsub(\".\", \"_\", pkgname, fixed = TRUE)\n glue(\"\n void R_init_{init_pkgname}(DllInfo *dll) {{\n R_registerRoutines(dll, NULL, NULL, NULL, QuickrEntries);\n R_useDynamicSymbols(dll, FALSE);\n }}\")\n }\n\n append(sources$c) <- init_fn\n\n sources <- lapply(sources, str_split_lines)\n\n src_files_written <- FALSE\n if (!file.exists(\"src\")) dir.create(\"src\")\n cbridges_filepath <- \"src/quickr_entrypoints.c\"\n if (!file.exists(cbridges_filepath) || !identical(sources$c, readLines(cbridges_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(cbridges_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$c, cbridges_filepath)\n cli::cli_inform(c(i = \"Updated {.file {cbridges_filepath}}\"))\n src_files_written <- TRUE\n }\n\n fsubs_filepath <- \"src/quickr_sub_routines.f90\"\n if (!file.exists(fsubs_filepath) || !identical(sources$f90, readLines(fsubs_filepath))) {\n unlink(sprintf(\"%s.o\", tools::file_path_sans_ext(fsubs_filepath)))\n unlink(pkg_dll_path(pkgname)) # TODO: this might fail on windows - need a fallback.\n writeLines(sources$f90, fsubs_filepath)\n cli::cli_inform(c(i = \"Updated {.file {fsubs_filepath}}\"))\n src_files_written <- TRUE\n }\n\n if (src_files_written) {\n for (i in seq_along(sys.calls())) {\n if (identical(sys.function(i), pkgload::load_all)) {\n defer(pkgload::load_all(), sys.frame(i), after = TRUE)\n rlang::return_from(sys.frame(i), value = invisible())\n break\n }\n }\n }\n invisible()\n}\n\npkg_dll_path <- function (pkgname) {\n file.path(\"src\", paste0(pkgname, .Platform$dynlib.ext))\n}\n\n\ncollector <- local({\n\n .collected <- NULL\n\n activate <- function(name = NULL) {\n .collected <<- list()\n attr(.collected, \"name\") <<- name\n }\n\n is_active <- function() {\n is.list(.collected)\n }\n\n add <- function(...) {\n .collected[[length(.collected)+1L]] <<- list(...)\n }\n\n get_collected <- function(clear = TRUE) {\n if (clear)\n on.exit(.collected <<- NULL)\n .collected\n }\n\n environment()\n})\n"], ["/quickr/R/sizes.R", "\n\n\ncheck_type_call <- function(cl) {\n if (length(cl) > 2)\n stop(\"only one variable can be declared per type() call\")\n args <- as.list(cl)[-1]\n if (length(names(args)) != 1)\n stop(\"name must be provided as: type(<name> = <mode>(<<dims>>)\")\n if (!is.call(args[[1]]) && as.character(args[[1]]) %in% .atomic_type_names)\n stop(\"only atomic modes are supported\")\n}\n\n\ntype_call_to_var <- function(cl) {\n check_type_call(cl)\n Variable(\n name = names(cl)[-1],\n mode = as.character(cl[[2L]][[1L]]),\n dims = unname(as.list(cl[[2]])[-1])\n )\n}\n\nvar_to_type_call <- function(var) {\n arg <- as.call(c(as.symbol(var@mode), var@dims))\n arg <- setNames(list(arg), var@name)\n as.call(c(quote(type), arg))\n}\n\n\nget_flattened_args <- function(cl) {\n # flatten exprs from `{` in usage like declare({ ... })`\n args <- as.list(cl)[-1]\n args <- lapply(args, function(e) {\n if (is_missing(e))\n NULL\n else if (is_call(e, quote(`{`)))\n get_flattened_args(e)\n else\n list(e)\n })\n unlist(args, recursive = FALSE)\n}\n\nself_evaluate <- function(...) sys.call()\n\nsubstitute_declared_sizes <- function(e) {\n stopifnot(is_call(e, quote(`{`)))\n\n aliases <- new.env(parent = emptyenv())\n eval_env <- new.env(parent = emptyenv())\n for(name in all.names(e, functions = TRUE, unique = TRUE))\n assign(name, self_evaluate, eval_env)\n eval_env <- new.env(parent = eval_env)\n for(name in all.names(e, functions = FALSE, unique = TRUE))\n assign(name, as.symbol(name), eval_env)\n\n eval_env$`{` <- function(...) {\n as.call(c(list(quote(`{`)), list(...)))\n }\n\n eval_env$declare <- function(...) {\n args <- get_flattened_args(sys.call())\n args <- lapply(args, function(e) {\n if (is_type_call(e)) {\n var <- type_call_to_var(e)\n var@dims <- imap(var@dims, function(size, axis) {\n size_name <- as.symbol(get_size_name(var, axis))\n if (is.symbol(size) && !exists(size, aliases)) {\n # user defined implicit size_name alias\n assign(as.character(size), size_name, aliases)\n size <- size_name\n } else if (is_scalar_na(size)) {\n size <- size_name\n } else if (is_wholenumber(size)) {\n size <- as.integer(size)\n }\n size\n })\n e <- var_to_type_call(var)\n }\n e\n })\n\n as.call(c(quote(declare), args))\n }\n\n e <- eval(e, eval_env)\n\n # Now the 'aliases' env is populated; go through and substitute\n # size aliases with the actual size name.\n eval_env$declare <- function(...) {\n as.call(lapply(sys.call(), function(e) {\n if (is_type_call(e))\n e <- substitute_(e, aliases)\n e\n }))\n }\n\n eval(e, eval_env)\n\n}\n\n\nr2size <- function(r, scope) {\n typeof(r) |> switch(\n integer = r,\n double = {\n if (is_wholenumber(r))\n as.integer(r)\n else\n stop(\"size must be an integer, found: \", r)\n },\n symbol = {\n if (is_size_name(r))\n return(r)\n var <- get(r, scope)\n if (var@mode != \"integer\" || !passes_as_scalar(var))\n warning(\"size is not an integer:\", as.character(r))\n if (var@is_arg && !var@modified)\n return(r)\n # TODO: add specific unit tests here\n if (identical(var@r, r))\n return(r)\n # make a best effort to use the r expression last assigned to the\n # symbol, or fail gracefully and return NA.\n # closure-locals with unspecified shape are declared allocatable\n # input and/or output args with unspecified shape signal an error.\n r2size(var@r, scope)\n },\n language = {\n as.character(r[[1]]) |> switch(\n `+` = , `-` = , `/` = , `*` = , `^` = , `%/%` = , `%%` = {\n args <- as.list(r)[-1]\n args <- lapply(args, r2size, scope)\n if (anyNA(rapply(args, as.list)))\n return(NA_integer_)\n cl <- as.call(c(r[[1]], args))\n if (all(map_lgl(args, is.atomic)))\n cl <- eval(cl, baseenv())\n cl\n },\n length = {\n var <- get(r[[2L]], scope)\n if (var@rank == 1)\n return(var@dims[[1L]])\n len <- reduce(var@dims, \\(d1, d2) call(\"*\", d1, d2))\n r2size(len, scope)\n },\n `[` = {\n # [ only works when paired with dim()\n if (!is_call(r[[2L]], quote(dim)))\n return(NA_integer_)\n var <- get(r[[2L]][[2L]], scope)\n axis <- r[[3]]\n if (!is_wholenumber(axis))\n return(NA_integer_)\n if (axis > var@rank)\n stop(\"insufficient rank of variable in \", deparse1(r))\n var@dims[[axis]]\n },\n # dim = {\n #\n # },\n nrow = {\n var <- get(r[[2L]], scope)\n var@dims[[1]]\n },\n ncol = {\n var <- get(r[[2L]], scope)\n var@dims[[2]]\n },\n NA_integer_)\n },\n NA_integer_\n )\n}\n\nr2dims <- function(r, scope) {\n if (is.call(r)) {\n as.character(r[[1]]) |> switch(\n dim = {\n var <- get(r[[2L]], scope)\n return(var@dims)\n },\n c = {\n args <- lapply(r[-1], r2dims, scope)\n dims <- unlist(args, recursive = FALSE)\n return(as.list(dims))\n },\n r <- list(r))\n }\n lapply(r, r2size, scope)\n}\n\nget_size_name <- function(var, axis = NULL, name = var@name, rank = var@rank) {\n stopifnot(is.null(axis) || is_wholenumber(axis) && axis > 0)\n if (is.null(axis) || rank == 1 && axis == 1)\n sprintf(\"%s__len_\", name)\n else {\n if (axis > rank) stop(\"axis must not be > rank\")\n sprintf(\"%s__dim_%i_\", name, axis)\n }\n}\n\n\n\n# TODO: allow syntax like:\n# declare(type(a, b, c = integer(1)))\n# or:\n# declare(type(a = , b = , c = integer(1)))\n"], ["/quickr/R/c-wrapper.R", "\nmake_c_bridge <- function(fsub, strict = TRUE, headers = TRUE) {\n stopifnot(inherits(fsub, FortranSubroutine))\n\n closure <- fsub@closure\n scope <- fsub@scope\n\n fsub_arg_names <- fsub@signature # arg names\n closure_arg_names <- names(formals(closure))\n\n c_body <- character()\n\n if (!all(closure_arg_names %in% fsub_arg_names))\n stop(\"Undeclared arguments: \", str_flatten_commas(setdiff(closure_arg_names, fsub_arg_names)))\n\n closure_arg_vars <- mget(closure_arg_names, scope)\n\n # first unpack all the input vars into named C variables (including sizes and pointer)\n append(c_body) <- lapply(closure_arg_vars, closure_arg_c_defs, strict = strict) |>\n rbind(\"\")\n\n ## TODO, might still need to define a length size for vars where rank>1, if in checks.\n\n # now do all size checks.\n append(c_body) <- lapply(closure_arg_vars, closure_arg_size_checks, scope = scope)\n\n # maybe define and allocate the output var\n n_protected <- 0L\n return_var <- get(closure_return_var_name(closure), scope)\n if (!return_var@name %in% closure_arg_names) {\n return_var@modified <- TRUE\n assign(return_var@name, return_var, scope)\n append(c_body) <- return_var_c_defs(return_var, fsub@scope)\n add(n_protected) <- 1L # allocated return var\n if (return_var@rank > 1)\n add(n_protected) <- 1L # allocated _dim_sexp\n }\n\n fsub_call_args <- fsub_arg_names |>\n lapply(\\(nm) paste0(nm, if (!is_size_name(nm)) \"__\")) |>\n unlist()\n\n if (length(fsub_call_args) > 3)\n fsub_call_args <- paste0(\"\\n \", fsub_call_args)\n\n append(c_body) <- c(\"\", glue(\"{fsub@name}({str_flatten_commas(fsub_call_args)});\"), \"\")\n if (n_protected > 0)\n append(c_body) <- glue(\"UNPROTECT({n_protected});\")\n append(c_body) <- glue(\"return {return_var@name};\")\n\n c_args <- paste(\"SEXP\", names(formals(closure)), collapse = \", \")\n c_body <- as_glue(str_flatten_lines(c_body))\n\n c_func_def <- glue(\"SEXP {fsub@name}_(SEXP _args) {c_block(c_body)}\")\n\n fsub_extern_decl <- fsub_extern_decl(fsub)\n\n c_headers <- glue::trim(r\"--(\n #define R_NO_REMAP\n #include <R.h>\n #include <Rinternals.h>\n\n\n )--\")\n\n as_glue(str_flatten_lines(c(\n if (headers) c_headers,\n fsub_extern_decl, \"\",\n c_func_def)\n ))\n}\n\n\nclosure_arg_c_defs <- function(var, strict = TRUE) {\n\n name <- var@name\n mode <- var@mode\n\n c_code <- character()\n\n name <- var@name\n SEXPTYPE <- sexptype(var@mode)\n protect <- glue(\"SETCAR(_args, {var@name});\")\n\n append(c_code) <- glue(\n \"// {name}\n _args = CDR(_args);\n SEXP {var@name} = CAR(_args);\")\n\n # first maybe duplicate or coerce the SEXP if needed.\n append(c_code) <- glue(\"if (TYPEOF({name}) != {SEXPTYPE}) {{\")\n append(c_code) <- indent(if (strict) {\n glue(r\"(\n Rf_error(\"typeof({name}) must be '{mode}', not '%s'\", R_typeToChar({name}));\n )\")\n } else {\n glue(\"{name} = Rf_coerceVector({name}, {SEXPTYPE});\n {protect}\")\n })\n\n\n if (var@modified) {\n dup <- glue('\n {name} = Rf_duplicate({name});\n {protect}\n ')\n\n if (strict) {\n append(c_code) <- c(\"}\", dup)\n } else {\n append(c_code) <- sprintf(\"} else %s\", dup)\n }\n\n } else {\n append(c_code) <- \"}\"\n }\n\n # define the variable that will be passed to the fsub\n append(c_code) <- glue(\n \"{fsub_arg_var_c_type(var)} {name}__ = {sexpdata(var@mode)}({name});\")\n\n\n if (var@rank == 1) {\n size_name <- get_size_name(var)\n append(c_code) <- glue(\"const R_xlen_t {size_name} = Rf_xlength({var@name});\")\n } else if (var@rank > 1) {\n append(c_code) <- glue(\n 'const int* const {var@name}__dim_ = ({{\n SEXP dim_ = Rf_getAttrib({var@name}, R_DimSymbol);\n if (Rf_length(dim_) != {var@rank}) Rf_error(\n \"{var@name} must be a {var@rank}D-array, but length(dim({var@name})) is %i\",\n (int) Rf_length(dim_));\n INTEGER(dim_);}});'\n )\n append(c_code) <- map_chr(seq_len(var@rank), \\(axis) {\n size_name <- get_size_name(var, axis)\n glue(\"const int {size_name} = {var@name}__dim_[{axis-1}];\")\n })\n } else {\n stop(\"bad rank\")\n }\n\n as_glue(str_flatten_lines(c_code))\n}\n\n\n\nclosure_arg_size_checks <- function(var, scope) {\n imap(var@dims, function(d, axis) {\n # axis is either:\n # - an integer\n # - a symbol of a size_name\n # - a call, consisting of only size_name symbols and basic arithmetic ops.\n size_name <- get_size_name(var, axis)\n\n if (is_scalar_integer(d)) {\n return(glue('\n if ({size_name} != {d})\n Rf_error(\"{friendly_size(var, axis)} must be {d}, not %0.f\",\n (double){size_name});'\n ))\n }\n\n if (is.symbol(d)) {\n if (as.character(d) == size_name) {\n # self-named size_name is expected to be passed along to subroutine\n return()\n } else {\n # it's a constraint for another size\n return(glue('\n if ({d} != {size_name})\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_name(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double){d});'\n ))\n }\n }\n\n if (is.call(d)) {\n size.c <- dims2c(list(d), scope)\n return(glue('{{\n const R_xlen_t expected = {size.c};\n if ({size_name} != expected)\n Rf_error(\"{as_friendly_size_name(size_name)} must equal {as_friendly_size_expression(d)},\"\n \" but are %0.f and %0.f\",\n (double){size_name}, (double)expected);\n }}'\n ))\n }\n\n stop(\"bad dim\")\n })\n}\n\n\n\n\nreturn_var_c_defs <- function(var, scope) {\n # allocate the return var.\n name <- var@name\n c_dims <- dims2c(var@dims, scope)\n c_len <- c_dims2c_len(c_dims)\n len_name <- get_size_name(var)\n\n c_code <- c(\n glue(\"const R_xlen_t {len_name} = {c_len};\"),\n glue(switch(\n var@mode,\n double = \"\n SEXP {name} = PROTECT(Rf_allocVector(REALSXP, {len_name}));\n double* {name}__ = REAL({name});\",\n integer = \"\n SEXP {name} = PROTECT(Rf_allocVector(INTSXP, {len_name}));\n int* {name}__ = INTEGER({name});\",\n complex = \"\n SEXP {name} = PROTECT(Rf_allocVector(CPLXSXP, {len_name}));\n Rcomplex* {name}__ = COMPLEX({name});\",\n logical = \"\n SEXP {name} = PROTECT(Rf_allocVector(LGLSXP, {len_name}));\n int* {name}__ = LOGICAL({name});\"\n )))\n\n if (var@rank > 1) {\n append(c_code) <- c_block(\n glue(\"\n const SEXP _dim_sexp = PROTECT(Rf_allocVector(INTSXP, {var@rank}));\n int* const _dim = INTEGER(_dim_sexp);\"\n ),\n imap(c_dims, function(d, i) {\n glue(\"_dim[{i-1}] = {d};\")\n }),\n glue(\"Rf_dimgets({var@name}, _dim_sexp);\")\n )\n }\n\n str_flatten_lines(c_code)\n}\n\n\n\n\ndims2c_eval_base_env <- new.env()\n\n\ndims2c_eval_base_env[[\"(\"]] <- baseenv()[[\"(\"]]\ndims2c_eval_base_env[[\"+\"]] <- function(e1, e2) glue(\"({e1} + {e2})\")\ndims2c_eval_base_env[[\"-\"]] <- function(e1, e2) glue(\"({e1} - {e2})\")\ndims2c_eval_base_env[[\"*\"]] <- function(e1, e2) glue(\"({e1} * {e2})\")\ndims2c_eval_base_env[[\"/\"]] <- function(e1, e2) glue(\"((double)({e1}) / (double)({e2}))\")\n# dividing integers truncates towards 0\ndims2c_eval_base_env[[\"%/%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} / (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"%%\"]] <- function(e1, e2) glue(\"((R_xlen_t){e1} % (R_xlen_t){e2})\")\ndims2c_eval_base_env[[\"^\"]] <- function(e1, e2) glue(\"({e1}**{e2})\")\n\n\ndims2c <- function(dims, scope) {\n if (!length(dims) || identical(dims, list(1L))) {\n return(list(NULL, \"1\"))\n }\n\n syms <- as.character(unique(unlist(lapply(dims, all.vars))))\n\n syms <- mget(syms, scope, ifnotfound = syms) |>\n lapply(function(var) {\n if (is_size_name(var)) {\n return(as.character(var))\n }\n # resolve a variable from scope (i.e., some other arg var)\n if (!inherits(var, Variable))\n stop(\"could not resolve size: \", var)\n glue(\"Rf_asInteger({var@name})\")\n # Should this be as double?\n # TODO: force this into a named c var, to avoid repeated calls\n })\n\n eval_env <- list2env(syms, parent = dims2c_eval_base_env)\n c_dims <- lapply(dims, function(d) {\n if (inherits(d, Variable))\n return(glue(\"Rf_asInteger({d@name})\"))\n eval(d, eval_env)\n })\n\n c_dims\n}\n\nc_dims2c_len <- function(c_dims) {\n if (length(c_dims) == 1)\n c_dims[[1L]]\n else\n paste0(\"(\", unlist(c_dims), \")\", collapse = \" * \" )\n # eval(Reduce(\\(a, b) { call(\"*\", as.symbol(a@name), as.symbol(b@name)) }, dims),\n # eval_env)\n}\n\n\n# --- utils ----\n\nc_block <- function(...) {\n as_glue(paste0(c(\"{\", indent(c(...)), \"}\"), collapse = \"\\n\"))\n}\n\n# is_var_size <- function(x) inherits(x, VariableSize)\n\npasses_as_scalar <- function(var) {\n var@rank == 0 || var@rank == 1 && identical(var@dims, list(1L))\n}\n\npasses_as_value <- function(var) {\n passes_as_scalar(var) && isFALSE(var@modified)\n}\n\nsexptype <- function(mode) {\n switch(mode,\n integer = \"INTSXP\",\n double = \"REALSXP\",\n complex = \"CPLXSXP\",\n logical = \"LGLSXP\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nsexpdata <- function(mode) {\n switch(mode,\n integer = \"INTEGER\",\n double = \"REAL\",\n complex = \"COMPLEX\",\n logical = \"LOGICAL\",\n stop(\"Unrecognized mode: \", mode))\n}\n\nis_size_name <- function(name) {\n if (is.symbol(name)) {\n name <- as.character(name)\n } else if (!is_string(name)) {\n return(FALSE)\n }\n\n grepl(\"(_len_|_dim_[0-9]+_)$\", name)\n}\n\nfriendly_size <- function(var, axis = NULL) {\n if (is.null(axis) || var@rank == 1 && axis == 1)\n glue(\"length({var@name})\")\n else\n glue(\"dim({var@name})[{axis}]\")\n}\n\nas_friendly_size_name <- function(size_name) {\n size_name <- as.character(size_name)\n if (endsWith(size_name, \"__len_\"))\n sprintf(\"length(%s)\", sub(\"__len_$\", \"\", size_name))\n else\n sub(\"^(.*)__dim_([0-9]+)_$\", \"dim(\\\\1)[\\\\2]\", size_name)\n}\n\nas_friendly_size_expression <- function(d) {\n stopifnot(is.call(d))\n nms <- all.names(d, functions = FALSE, unique = TRUE)\n friendly_substitutions <- new.env(parent = emptyenv())\n for(name in nms)\n if (is_size_name(name))\n assign(name, str2lang(as_friendly_size_name(name)), friendly_substitutions)\n d <- substitute_(d, friendly_substitutions)\n d <- call(\"(\", d)\n deparse1(d)\n}\n\nclosure_return_var_name <- function(closure) {\n return_var_name <- last(body(closure))\n if (!is.symbol(return_var_name))\n stop(\"return value must be a symbol\")\n as.character(return_var_name)\n}\n\n\nfsub_arg_var_c_type <- function(var) {\n type <- switch(var@mode,\n double = \"double*\",\n integer = \"int*\",\n complex = \"Rcomplex*\",\n logical = \"int*\",\n )\n\n # the first const declares that the pointed to values can't be modified\n # (the array values are read only)\n # the second const declares that the pointer itself can't be modified\n # (the fsub can never move/reallocate the array, so this const is always present)\n paste0(c(if (!var@modified) \"const\", type, \"const\"),\n collapse = \" \")\n}\n\nfsub_extern_decl <- function(fsub) {\n fsub_arg_names <- fsub@signature # arg names\n scope <- fsub@scope\n\n fsub_c_sig <- map_chr(fsub_arg_names, function(name) {\n if (is_size_name(name)) {\n type <- if (endsWith(\"__len_\", name))\n \"R_xlen_t\" else \"R_len_t\"\n glue(\"const {type} {name}\")\n } else {\n var <- get(name, fsub@scope)\n glue(\"{fsub_arg_var_c_type(var)} {var@name}__\")\n }\n })\n if (length(fsub_c_sig) >= 3L)\n fsub_c_sig <- paste0(\"\\n \", fsub_c_sig)\n\n glue(\"extern void {fsub@name}({str_flatten_commas(fsub_c_sig)});\")\n}\n"], ["/quickr/R/zzz.R", "# # ' @export\n# `@.default` <- function(x, name) {\n# if (isS4(x))\n# methods::slot(x, name)\n# else\n# attr(x, name, TRUE)\n# }\n#\n# # ' @export\n# `@<-.default` <- function(x, name, value) {\n# if (isS4(x))\n# methods::`slot<-`(x, name, value = value)\n# else\n# `attr<-`(x, name, value)\n# }\n#\n# # ' @importFrom utils .AtNames findMatches\n# .AtNames.default <- function(x, pattern = \"\") {\n# if (isS4(x))\n# findMatches(pattern, methods::slotNames(x))\n# else\n# findMatches(pattern, names(attributes(x)))\n# }\n#\n# on_load_register_.AtNames.default <- function() {\n# # if we register via NAMESPACE, we get warning\n# # about overwriting utils:::.AtNmaes.default\n# registerS3method(\".AtNames\", \"default\", .AtNames.default)\n# }\n\n.onLoad <- function(...) {\n S7::methods_register()\n asNamespace(\"dotty\")$dotify()\n # on_load_register_.AtNames.default()\n}\n\n"], ["/quickr/R/subroutine.R", "\n\nnew_fortran_subroutine <- function(name, closure, parent = emptyenv()) {\n\n\n check_all_var_names_valid(closure)\n\n # translate body, and populate scope with variables\n body <- body(closure)\n\n # defuse calls like `-1` and `1+1i`. Not really necessary, but simplifies downstream a little.\n body <- defuse_numeric_literals(body)\n\n # TODO: try harder here to use one of the input vars as the output var\n body <- ensure_last_expr_sym(body)\n\n # update closure with sym return value\n base::body(closure) <- body\n # body <- rlang::zap_srcref(body)\n\n scope <- new_scope(closure, parent)\n\n # inject symbols for var sizes in declare calls, so like:\n # declare(type(foo = integer(nr, NA)),\n # type(bar = integer(nr, 3)))\n # become:\n # declare(type(foo = integer(foo_dim_1_, foo_dim_2_)),\n # type(bar = integer(foo_dim_1_, 3L)))\n body <- substitute_declared_sizes(body)\n body <- r2f(drop_last(body), scope)\n\n # check all input vars were declared\n # TODO: this check might be too late, because r2f() might throw cryptic errors\n # when handling undeclared variables. Either throw better errors from r2f(), or\n # handle all declares first\n for(arg_name in names(formals(closure))) {\n if (is.null(var <- get0(arg_name, scope)))\n stop(\"arg not declared: \", arg_name)\n }\n\n # figure out the return variable.\n if (is.symbol(last_expr <- last(body(closure)))) {\n return_var <- get(last_expr, scope)\n return_var@is_return <- TRUE\n scope[[as.character(last_expr)]] <- return_var\n } else {\n # lots we can still do here, just not implemented yet.\n stop(\"last expression in the function must be a bare symbol\")\n }\n\n manifest <- r2f.scope(scope)\n fsub_arg_names <- attr(manifest, \"signature\", TRUE)\n\n used_iso_bindings <- unique(unlist(use.names = FALSE, list(\n lapply(scope, function(var) {\n list(\n switch(\n var@mode,\n double = \"c_double\",\n integer = \"c_int\",\n logical = if (var@name %in% fsub_arg_names)\n \"c_int\",\n complex = \"c_double_complex\",\n raw = \"c_int8_t\"\n ),\n lapply(var@dims, function(size) {\n syms <- all.vars(size)\n c(if (any(grepl(\"__len_$\", syms))) \"c_ptrdiff_t\",\n if (any(grepl(\"__dim_[0-9]+_$\", syms))) \"c_int\")\n })\n )\n }))))\n\n # check for literal kinds\n if (!\"c_int\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+_c_int\\\\b\", body))\n append(used_iso_bindings) <- \"c_int\"\n }\n if (!\"c_double\" %in% used_iso_bindings) {\n if (grepl(\"\\\\b[0-9]+\\\\.[0-9]+_c_double\\\\b\", body))\n append(used_iso_bindings) <- \"c_double\"\n }\n used_iso_bindings <- sort(used_iso_bindings, method = \"radix\")\n\n subroutine <- glue(\"\n subroutine {name}({str_flatten_commas(fsub_arg_names)}) bind(c)\n use iso_c_binding, only: {str_flatten_commas(used_iso_bindings)}\n implicit none\n\n {indent(manifest)}\n\n {indent(body)}\n end subroutine\n \")\n\n subroutine <- insert_fortran_line_continuations(subroutine)\n\n FortranSubroutine(\n subroutine,\n name = name,\n signature = fsub_arg_names,\n scope = scope,\n closure = closure\n )\n}\n\ninsert_fortran_line_continuations <- function(code, preserve_attributes = TRUE) {\n attrs_in <- attributes(code)\n\n code <- as.character(code)\n lines <- str_split_lines(code)\n lines <- trimws(lines, \"right\")\n\n if (any(too_long <- nchar(lines) > 132)) {\n # remove leading indentation\n lines[too_long] <- trimws(lines[too_long], \"left\")\n\n # move trailing comment at the end\n lines[too_long] <- sub(\"^(.*)!(.*)$\", \"!\\\\2\\n\\\\1\", lines[too_long])\n lines <- str_split_lines(lines)\n\n # maximum 255 continuations are allowed\n for (i in 1:256) {\n if (!any(too_long <- nchar(lines) > 132))\n break\n lines[too_long] <- sub(\"^(.{1,130})\\\\s\", \"\\\\1 &\\n\", lines[too_long])\n lines <- str_split_lines(lines)\n }\n if (i > 255L)\n stop(\"Too long line encountered. Please split long expressions into a sequence of smaller expressions.\")\n }\n\n code <- str_flatten_lines(lines)\n if (preserve_attributes)\n attributes(code) <- attrs_in\n code\n}\n\n"], ["/quickr/R/preprocess-lang.R", "\n\ndefuse_numeric_literals <- function(e) {\n if (is.call(e)) {\n e <- as.call(lapply(e, defuse_numeric_literals))\n if (is.symbol(e1 <- e[[1L]]) &&\n as.character(e1) %in% c(\"+\", \"-\", \"*\", \"/\", \"%%\", \"%/%\", \"^\") &&\n all(map_lgl(e[-1L], is.atomic))) {\n e <- eval(e, baseenv())\n }\n }\n e\n}\n\n\nensure_last_expr_sym <- function(bdy) {\n if (!is_call(bdy, quote(`{`)))\n stop(\"bad body, needs {\")\n if (!is.symbol(last_expr <- last(bdy))) {\n bdy[[length(bdy)]] <- call(\"<-\", quote(out_), last_expr)\n bdy[[length(bdy) + 1L]] <- quote(out_)\n }\n bdy\n}\n\n\nwhole_doubles_to_ints <- function(x) {\n walker <- function(x) {\n switch(\n typeof(x),\n double = if (trunc(x) == x) as.integer(x),\n language = as.call(lapply(x, walker)),\n list = lapply(x, walker),\n x\n )\n }\n walker(x)\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:15:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(closure, parent = emptyenv()) {}", "code_description": "This code segment functions to: Create a managed execution context with ordered variable tracking, automatic temporary identifier generation, and type-constrained assignment validation for symbolic objects."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nnew_scope <- function(closure, parent = emptyenv()) {\n env <- new_ordered_env(parent = parent)\n attr(env, \"closure\") <- closure\n class(env) <- c(\"quickr_scope\", class(env))\n env\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-16-47"}, "editdistance_info": {"edit_distance": 16.7568, "calculate_time": "2025-08-21 01:16:47", "true_code_clean": "function(closure, parent = emptyenv()) {\n scope <- new_ordered_env(parent = parent)\n class(scope) <- unique(c(\"quickr_scope\", class(scope)))\n attr(scope, \"closure\") <- closure\n attr(scope, \"get_unique_var\") <- local({\n i <- 0L\n function(...) {\n name <- paste0(\"tmp\", i <<- i + 1L, \"_\")\n (scope[[name]] <- Variable(..., name = name))\n }\n })\n attr(scope, \"assign\") <- function(name, value) {\n stopifnot(inherits(value, Variable), is.symbol(name) || is_string(name))\n name <- as.character(name)\n if (exists(name, scope))\n check_assignment_compatible(get(name, scope), value)\n value@name <- name\n assign(name, value, scope)\n }\n scope\n}", "predict_code_clean": "new_scope <- function(closure, parent = emptyenv()) {\n env <- new_ordered_env(parent = parent)\n attr(env, \"closure\") <- closure\n class(env) <- c(\"quickr_scope\", class(env))\n env\n}"}}