jupyter-xeus / xeus-r

Jupyter kernel for the R programming language
Other
40 stars 5 forks source link

organize R code in R package #81

Open romainfrancois opened 2 months ago

romainfrancois commented 2 months ago

closes #32

This puts the support R code into an R package called hera instead of having volatile R code that is source() from the directory. The plan is for hera to be tested as a standalone package with typical R code tools, i.e. testthat ...

So currently, the kernel void interpreter::configure_impl() will try to load hera:

void interpreter::configure_impl()
{
    SEXP sym_library = Rf_install("library");
    SEXP chr_hera = PROTECT(Rf_mkString("hera"));
    SEXP call_library_hera = PROTECT(Rf_lang2(sym_library, chr_hera));

    SEXP sym_try = Rf_install("try");
    SEXP sym_silent = Rf_install("silent");
    SEXP call_try = PROTECT(Rf_lang3(sym_try, call_library_hera, Rf_ScalarLogical(TRUE)));
    SET_TAG(CDDR(call_try), sym_silent);

    SEXP loaded = PROTECT(Rf_eval(call_try, R_GlobalEnv));
    if (!Rf_inherits(loaded, "try-error")) {
        SEXP sym_asNamespace = Rf_install("asNamespace");
        SEXP call_as_Namespace = PROTECT(Rf_lang2(sym_asNamespace, chr_hera));

        env_hera = PROTECT(Rf_eval(call_as_Namespace, R_GlobalEnv));
        R_PreserveObject(env_hera);
        UNPROTECT(2);
    }

    UNPROTECT(4);
}

And then e.g. execute_request_impl() will call the R function execute that lives in hera:

SEXP result = invoke_hera_fn("execute", code_, execution_counter_, silent_);

Then the R code might need to call the routines made available by xeusr, e.g.

publish_stream <- function(name, text) {
  .Call("xeusr_publish_stream", name, text, PACKAGE = "(embedding)")
}

This is all similar to what was, but having it in a proper package will help.

For testing purposes, i.e. when R is not embedded, and therefore those routines are not available, we'll have to replace them with mockups.

An issue I have with this, is that e need to make sure that the 📦 is installed, so I probably need to investigate that.