6

I wish I knew how to make this example smaller, but I don't understand the problem well enough to do that.

I have a package that rewrites R functions to make them tail-recursive: tailr. It does a bit of analysis of a recursive function and then translates it into a looping function. For example, it will translate this factorial function

factorial <- function(n, acc) {
    if (n <= 1) acc
    else factorial(n - 1, acc * n)
}

into this version

factorial <- function(n, acc) {
    .tailr_n <- n
    .tailr_acc <- acc
    callCC(function(escape) {
        repeat {
            n <- .tailr_n
            acc <- .tailr_acc
            if (n <= 1)
                escape(acc)
            else {
                .tailr_n <<- n - 1
                .tailr_acc <<- acc * n
            }
        }
    })
}

The generated function is not pretty, but it does work.

My problem is if I write a package that uses the transformation, one that contains only these lines of R:

#' Computes the factorial.
#' @param n A number
#' @param acc Accumulator to make the function tail-recursive
#' @return factorial of n
#' @export
factorial <- function(n, acc) {
    if (n <= 1) acc
    else factorial(n - 1, acc * n)
}

#' Computes the factorial.
#' @param n A number
#' @return factorial of n
#' @param acc Accumulator to make the function tail-recursive
#' @export
factorial_loop <- tailr::loop_transform(factorial)

running devtools::check() give me this error:

Error in attr(e, "srcref")[[i]] : subscript out of bounds
Calls: <Anonymous> ... <Anonymous> -> collectUsage -> collectUsageFun -> walkCode -> h
Execution halted

If I put a dummy version of the transformation into the package, I do not get an error

dummy_transform_body <- function(expr) {
    rlang::expr({
        .tailr_n <- n
        .tailr_acc <- acc
        callCC(function(escape) {
            repeat {
                n <- .tailr_n
                acc <- .tailr_acc
                if (n <= 1)
                    escape(acc)
                else {
                    .tailr_n <<- n - 1
                    .tailr_acc <<- acc * n
                }
            }
        })
    })
}
dummy_transform <- function(fun) {
    fun_q <- rlang::enquo(fun)

    new_fun_body <- dummy_transform_body(body(fun))
    result <- rlang::new_function(
        args = formals(fun),
        body = new_fun_body,
        env = rlang::get_env(fun_q)
    )

    result
}

#' Computes the factorial.
#' @param n A number
#' @return factorial of n
#' @param acc Accumulator to make the function tail-recursive
#' @export
factorial_loop_dummy <- dummy_transform(factorial)

I don't see any differences between the two functions, so I am puzzled why the check accepts the dummy but not the real version.

> body(factorial_loop) == body(factorial_loop_dummy)
[1] TRUE
> environment(factorial_loop)
<environment: namespace:Test>
> environment(factorial_loop_dummy)
<environment: namespace:Test>
> formals(factorial_loop)
$n


$acc


> formals(factorial_loop_dummy)
$n


$acc


> attributes(factorial_loop())
Error in factorial_loop() : argument "n" is missing, with no default
> attributes(factorial_loop)
NULL
> attributes(factorial_loop_dummy)
NULL

The error mentions the attribute srcref, but neither transformed function has any attributes. If I explicitly set the srcref attribute it doesn't help with the error though.

Any ideas, anyone?

Update 2018/03/20:

The problem seems to be with the quasi-quotation splicing in my transformation function. If I uncomment that, the !!! statements below, and manually insert the cases for the factorial, then the error goes away.

dummy_transform_body <- function(fun_expr, info) {
    vars <- names(formals(info$fun))
    tmp_assignments <- vector("list", length = length(vars))
    locals_assignments <- vector("list", length = length(vars))
    for (i in seq_along(vars)) {
        local_var <- as.symbol(vars[[i]])
        tmp_var <- parse(text = paste(".tailr_", vars[[i]], sep = ""))[[1]]
        tmp_assignments[[i]] <- rlang::expr(rlang::UQ(tmp_var) <- rlang::UQ(local_var))
        locals_assignments[[i]] <- rlang::expr(rlang::UQ(local_var) <- rlang::UQ(tmp_var))
    }

    # this would be a nice pipeline, but it is a bit much to require
    # magrittr just for this
    fun_expr <- make_returns_explicit(fun_expr, FALSE, info)
    fun_expr <- simplify_returns(fun_expr, info)
    fun_expr <- handle_recursive_returns(fun_expr, info)
    fun_expr <- returns_to_escapes(fun_expr, info)
    fun_expr <- simplify_nested_blocks(fun_expr)

    rlang::expr({
        #!!! tmp_assignments
        .tailr_n <- n
        .tailr_acc <- acc
        callCC(function(escape) {
            repeat {
                #!!! locals_assignments
                n <<- .tailr_n
                acc <<- .tailr_acc
                !! fun_expr
                next
            }
        })
    })
}

Another Update:

...Deleted the previous update... The hack with putting the splicing inside another bock doesn't work for me any longer...

Yet another update...

Ok, I still have absolutely no idea why the splicing isn't working. I made other dummy-functions where it did. So I am really interested if someone has any ideas. In any case, I managed to rewrite my tailr function to avoid !!! and that seems to work now.

    repeat_body <- as.call(
         c(`{`, locals_assignments, fun_expr, quote(next))
     )
     call_cc_stmt <- rlang::expr(
         callCC(function(escape) {
             repeat {
                 !!repeat_body
             }
         })
     )
     as.call(
         c(`{`, tmp_assignments, call_cc_stmt)
     )

This is just a lot less elegant and the generated code is uglier--but I hide that by setting srcref to the original code, so no one need ever know.

3
  • I tried putting the dummy_transform function in another package, but CMD CHECK still accepts it. So the problem must be in tailr, somehow. I will dig further... Mar 20, 2018 at 6:07
  • Sorry for the naive question, but do you think the issue may be in the fact that factorial_loop <- tailr::loop_transform(factorial) calls loop_transform from an external package for which the "source reference" may or may not be visible to your new package, whereas dummy_transform is defined directly in the same package as factorial_loop? Aug 27, 2018 at 1:37
  • I don't think this is it. In the example here, I do indeed define dummy_transform in the same package, but I have packages where I use loop_transform where the second version passes checks but the first doesn't. Anyway, I am just using that and then it works, I guess Aug 27, 2018 at 6:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.