Skip to main content

r_eval_str

Function r_eval_str 

Source
pub unsafe fn r_eval_str(code: &str, env: SEXP) -> Result<SEXP, String>
Expand description

Parse a string of R source and evaluate it in env.

This is the runtime workhorse behind the r_str! and r! macros. It performs the full R_ParseVector → check status → Rf_eval ladder with correct GC protection on every intermediate SEXP, so callers never have to hand-roll OwnedProtect around the parse tree.

Only the last top-level expression’s value is returned (matching R’s eval(parse(text = ...)) semantics): each parsed expression is evaluated in order so that side effects (assignments, library(), …) take effect, and the value of the final one is returned. An empty / whitespace-only string yields R_NilValue.

§Safety

  • Must be called from (or routed to) the R main thread. The parse and eval FFI calls go through the checked #[r_ffi_checked] variants, which serialize onto the R thread via with_r_thread, so calling from a worker thread is sound — but the returned SEXP must not outlive the R session.
  • env must be a valid ENVSXP.

§Returns

  • Ok(SEXP) with the value of the last expression (unprotected — the caller should protect it if further allocations will occur before use).
  • Err(String) if parsing fails (syntax error / incomplete input) or if evaluation raises an R error. The error is captured via R_tryEvalSilent + geterrmessage(), so it never longjmps through Rust frames.

§Example

use miniextendr_api::expression::r_eval_str;
use miniextendr_api::sys::R_GlobalEnv;

unsafe {
    let three = r_eval_str("1L + 2L", R_GlobalEnv)?;
    // three is an INTSXP holding 3
}