rextendr

repository·main·Indexed 42 days ago

https://github.com/extendr/rextendr

A tool that allows developers to call Rust code directly from R. It enables the creation of high-performance R functions using Rust via the rust_function() API and provides a specialized extendr chunk type for knitr to write and evaluate Rust code within R Markdown documents.

Tokens
1.3K
Snippets
6
Records
7
Agent score
4%

What's inside rextendr

  1. Silence verbose cli output

    main

    Because rextendr uses {cli} for verbose user information, functions should provide a quiet argument (defaulting to FALSE). When a user sets quiet = TRUE, all {cli} output should be suppressed.

    To implement silencing within the package, use the helper function local_quiet_cli(quiet). When quiet = TRUE, all {cli} output is suppressed.

    # Example usage pattern for functions
    # (Implementation detail: use local_quiet_cli(quiet))
  2. Install rextendr

    main

    You can install the release version of rextendr from CRAN, r-universe, or GitHub. Note that to execute Rust code, you must also have a working Rust toolchain set up (refer to libR-sys installation instructions for details).

    # From CRAN
    install.packages("rextendr")
    
    # Using remotes from CRAN
    remotes::install_cran("rextendr")
    
    # From r-universe
    install.packages("rextendr", repos = c("https://extendr.r-universe.dev", "https://cloud.r-project.org"))
    
    # Latest development version from GitHub
    remotes::install_github("extendr/rextendr")
  3. Communicate status and information using cli functions

    main

    rextendr uses the {cli} package to format user-facing messages, which are typically routed through rlang::inform(). Use the following ui_*() functions to communicate different states to the user:

    • cli::cli_alert_success(): Communicate successful operations (e.g., writing a file).
    • cli::cli_alert_info(): Provide additional information.
    • cli::cli_alert_warning(): Warn the user (note: this emits a message condition, not a warning).
    • cli::cli_ul(): Indicate that user action is required.
    • cli::cli_alert_danger(): Inform the user that something went wrong (note: this emits a message condition, not an error).

    {cli} supports glue-based interpolation and inline text formatting.

  4. Use the extendr knitr chunk type

    main

    The rextendr package provides a specialized extendr chunk type for knitr. This allows you to write, compile, and evaluate Rust code directly within R Markdown documents. The output of the Rust code is then integrated into the knitted document.

    ```{extendr}
    rprintln!("Hello from Rust!");
    
    let x = 5;
    let y = 7;
    let z = x*y;
    
    z
    ```
  5. Throw errors using cli_abort() with rextendr_error class

    main

    When an error occurs, use cli::cli_abort() to pass the error. To maintain consistency with rextendr, you must specify the class rextendr_error. You can provide structured error details by passing a named vector to the message argument, which allows for specific error components and bulleted suggestions.

    cli::cli_abort(
      c(
        "Unable to register the extendr module.",
        "x" = "Could not find file {.file src/entrypoint.c}.",
        "*" = "Are you sure this package is using extendr Rust code?"
      ),
      class = "rextendr_error"
    )
  6. Check Rust toolchain status with rust_sitrep()

    main
    Use rust_sitrep() to verify that your Rust toolchain (rustup, cargo) and required targets are correctly configured for rextendr. This is a recommended first step after installation to ensure your environment can compile and run Rust code within R.
    rust_sitrep()
  7. Define and call Rust functions from R using rust_function()

    main

    The rust_function() API allows you to define Rust code directly within an R session. Once defined, the function becomes available in your R environment as if it were a native R function.

    Key arguments:

    • code: The Rust function definition as a string.
    • use_dev_extendr: Boolean. If TRUE, uses the development version of extendr from GitHub.
    • features: String. Enables specific Rust crate features (e.g., "either").
    library(rextendr)
    
    # Basic example
    rust_function("fn add(a:f64, b:f64) -> f64 { a + b }")
    add(2.5, 4.7)
    # [1] 7.2
    
    # Advanced example with features and dev version
    rust_function(
      "fn get_sum(x : Either<Integers, Doubles>) -> Either<Rint, Rfloat> {
          match x {
              Either::Left(x) => Either::Left(x.iter().sum()),
              Either::Right(x) => Either::Right(x.iter().sum()),
          }
      }",
      use_dev_extendr = TRUE,
      features = "either"
    )