Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
R: Rscript apps, through the C bridge and base R (#58)
chessMan71d3a427ee06
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9fb711a..3c93475 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -45,6 +45,9 @@ jobs:- uses: actions/setup-dotnet@v6with:dotnet-version: "10.0.x"+ - uses: r-lib/actions/setup-r@v2+ with:+ r-version: release- uses: gradle/actions/setup-gradle@v6- uses: Swatinem/rust-cache@v2- run: cargo fmt --check@@ -175,6 +178,20 @@ jobs:$fa disablegit diff --exit-code srctest -z "$(git status --porcelain .)"+ - name: end to end, R+ working-directory: examples/fuzzy-dedupe-r+ run: |+ fa=../../target/release/fast-anything+ $fa scan -- Rscript app.R+ $fa port+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs+ $fa verify+ $fa enable+ Rscript app.R+ $fa bench --runs 2+ $fa disable+ git diff --exit-code fuzzy.R+ test -z "$(git status --porcelain .)"- name: end to end, C#working-directory: examples/fuzzy-dedupe-csrun: |diff --git a/README.md b/README.mdindex a44301b..5ccadd8 100644--- a/README.md+++ b/README.md@@ -12,7 +12,7 @@<a href="https://www.npmjs.com/package/@el4cteo/fast-anything"><img src="https://img.shields.io/npm/v/@el4cteo/fast-anything?color=f74c00&label=npm" alt="npm"></a><a href="https://crates.io/crates/fast-anything"><img src="https://img.shields.io/crates/v/fast-anything?color=f74c00" alt="crates.io"></a><a href="https://github.com/EL4CTEO/fast-anything/actions/workflows/ci.yml"><img src="https://github.com/EL4CTEO/fast-anything/actions/workflows/ci.yml/badge.svg" alt="CI"></a>- <img src="https://img.shields.io/badge/Python%20%C2%B7%20Node%20%C2%B7%20TypeScript%20%C2%B7%20Ruby%20%C2%B7%20Java%20%C2%B7%20Kotlin%20%C2%B7%20Go%20%C2%B7%20PHP%20%C2%B7%20C%20%C2%B7%20C%2B%2B%20%C2%B7%20C%23-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Kotlin, Go, PHP, C, C++, C#">+ <img src="https://img.shields.io/badge/Python%20%C2%B7%20Node%20%C2%B7%20TypeScript%20%C2%B7%20Ruby%20%C2%B7%20Java%20%C2%B7%20Kotlin%20%C2%B7%20Go%20%C2%B7%20PHP%20%C2%B7%20C%20%C2%B7%20C%2B%2B%20%C2%B7%20C%23%20%C2%B7%20R-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Kotlin, Go, PHP, C, C++, C#, R"><img src="https://img.shields.io/badge/Claude%20Code-plugin-d97757" alt="Claude Code plugin"><img src="https://img.shields.io/badge/MCP-server-555" alt="MCP server"><a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-555" alt="MIT"></a>@@ -35,7 +35,7 @@ Ports are compiled with your Rust toolchain ([rustup](https://rustup.rs)).## Use```sh-fast-anything go --agent claude -- python app.py # or: -- node app.ts / bun app.ts / deno run -A app.ts / ruby app.rb / java App.java / mvn exec:java / gradle run / go run . / php app.php / clang -O2 main.c+fast-anything go --agent claude -- python app.py # or: -- node app.ts / bun app.ts / deno run -A app.ts / ruby app.rb / java App.java / mvn exec:java / gradle run / go run . / php app.php / clang -O2 main.c / Rscript app.R```Or step by step:@@ -101,12 +101,13 @@ fast-anything ports the outermost loop it can, not the tiny function called insi| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ || C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ || C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |+| R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed | ✅ |It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s (dataclasses, NamedTuples and numeric NumPy arrays count as plain data), in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.With Intel oneAPI on Windows, run fast-anything from a shell where `setvars.bat` ran (it sets up the linker). SYCL kernels run on the device and aren't ported; with `-fsycl`, only host functions are profiled and ported.-Ruby, Java, Go, PHP, C, C++ and C# need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.+Ruby, Java, Go, PHP, C, C++, C# and R need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.## Licensediff --git a/examples/fuzzy-dedupe-r/app.R b/examples/fuzzy-dedupe-r/app.Rnew file mode 100644index 0000000..49f956b--- /dev/null+++ b/examples/fuzzy-dedupe-r/app.R@@ -0,0 +1,29 @@+# Find near-duplicate customer names, the slow way.+# Rscript app.R+source("fuzzy.R")++FIRST <- c("Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid")+LAST <- c("Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka", "Wang",+ "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen")++make_names <- function(count, seed = 7) {+ set.seed(seed)+ vapply(seq_len(count), function(k) {+ name <- paste(sample(FIRST, 1), sample(LAST, 1))+ if (runif(1) < 0.35) {+ i <- sample.int(nchar(name), 1)+ k <- sample.int(10, 1)+ substr(name, i, i) <- substr("aeiourstln", k, k)+ }+ name+ }, "")+}++if (sys.nframe() == 0) {+ names <- make_names(300)+ pairs <- find_duplicates(names)+ cat(length(names), "names,", length(pairs), "likely duplicate pairs\n")+ shown <- Filter(function(p) names[p[1]] != names[p[2]], pairs)+ for (p in head(shown, 5)) cat(" ", names[p[1]], "~", names[p[2]], "\n")+}diff --git a/examples/fuzzy-dedupe-r/fuzzy.R b/examples/fuzzy-dedupe-r/fuzzy.Rnew file mode 100644index 0000000..42a6ce7--- /dev/null+++ b/examples/fuzzy-dedupe-r/fuzzy.R@@ -0,0 +1,39 @@+# Fuzzy string matching helpers.++# Edit distance: how many inserts, deletes or substitutions turn a into b.+levenshtein <- function(a, b) {+ a <- strsplit(a, "")[[1]]+ b <- strsplit(b, "")[[1]]+ if (length(a) < length(b)) {+ t <- a+ a <- b+ b <- t+ }+ previous <- 0:length(b)+ for (i in seq_along(a)) {+ current <- c(i, integer(length(b)))+ for (j in seq_along(b)) {+ current[j + 1] <- min(previous[j + 1] + 1, current[j] + 1, previous[j] + (a[i] != b[j]))+ }+ previous <- current+ }+ previous[length(previous)]+}++normalize <- function(name) {+ words <- strsplit(tolower(name), "[ \t\n\r]+")[[1]]+ paste(words[nzchar(words)], collapse = " ")+}++# Index pairs (counting from 1, as R does) of names within max_distance edits of each other.+find_duplicates <- function(names, max_distance = 2) {+ clean <- vapply(names, normalize, "", USE.NAMES = FALSE)+ pairs <- list()+ n <- length(clean)+ for (i in seq_len(max(n - 1, 0))) {+ for (j in (i + 1):n) {+ if (levenshtein(clean[i], clean[j]) <= max_distance) pairs[[length(pairs) + 1]] <- c(i, j)+ }+ }+ pairs+}diff --git a/examples/fuzzy-dedupe-r/reference/port.rs b/examples/fuzzy-dedupe-r/reference/port.rsnew file mode 100644index 0000000..3d130b7--- /dev/null+++ b/examples/fuzzy-dedupe-r/reference/port.rs@@ -0,0 +1,58 @@+//! Reference port of find_duplicates (with levenshtein and normalize inside it): what a good+//! agent run produces. CI uses it to test the pipeline without an agent.++use crate::r::{List, Vector};++/// R's normalize(): tolower, split on runs of " \t\n\r", drop empty words, join with " ".+/// NA goes through paste() as the text "NA".+fn normalize(name: Option<&str>) -> Vec<char> {+ let Some(name) = name else { return "NA".chars().collect() };+ let mut out = Vec::with_capacity(name.len());+ for word in name.split([' ', '\t', '\n', '\r']).filter(|w| !w.is_empty()) {+ if !out.is_empty() {+ out.push(' ');+ }+ // R's tolower maps one character to one character+ out.extend(word.chars().map(|c| {+ let mut lower = c.to_lowercase();+ if lower.len() == 1 { lower.next().unwrap_or(c) } else { c }+ }));+ }+ out+}++/// Edit distance, one row on the shorter side.+fn distance(a: &[char], b: &[char], row: &mut Vec<usize>) -> usize {+ let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };+ row.clear();+ row.extend(0..=short.len());+ for (i, ca) in long.iter().enumerate() {+ let mut diagonal = row[0];+ row[0] = i + 1;+ for (j, cb) in short.iter().enumerate() {+ let above = row[j + 1];+ row[j + 1] = (above + 1).min(row[j] + 1).min(diagonal + usize::from(ca != cb));+ diagonal = above;+ }+ }+ row[short.len()]+}++pub fn find_duplicates(names: Vector<Option<String>>, max_distance: Option<f64>) -> Result<List<Vec<(i64, i64)>>, String> {+ let clean: Vec<Vec<char>> = names.iter().map(|n| normalize(n.as_deref())).collect();+ let mut pairs = Vec::new();+ if clean.len() < 2 {+ return Ok(List(pairs));+ }+ // levenshtein(...) <= NA is NA, and if (NA) stops+ let max = max_distance.ok_or("missing value where TRUE/FALSE needed")?;+ let mut row = Vec::new();+ for i in 0..clean.len() - 1 {+ for j in i + 1..clean.len() {+ if distance(&clean[i], &clean[j], &mut row) as f64 <= max {+ pairs.push((i as i64 + 1, j as i64 + 1));+ }+ }+ }+ Ok(List(pairs))+}diff --git a/src/backend.rs b/src/backend.rsindex eedac2a..0a01af6 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -4,7 +4,7 @@use crate::hotspot::Hotspot;use crate::state::{Ctx, Port, Verify};use crate::util::{output, tail};-use crate::{cfamily, csharp, golang, java, kotlin, node, php, python, ruby};+use crate::{cfamily, csharp, golang, java, kotlin, node, php, python, r, ruby};use anyhow::{Context, Result, bail, ensure};use serde::{Deserialize, Serialize};use std::fs;@@ -25,6 +25,7 @@ pub enum Lang {Cpp,#[serde(rename = "csharp")]CSharp,+ R,Kotlin,}@@ -75,13 +76,15 @@ impl Lang {Ok(Lang::Php)} else if csharp::is_csharp(program) {Ok(Lang::CSharp)+ } else if r::is_r(program) {+ Ok(Lang::R)} else if let Some(lang) = cfamily::detect(program) {Ok(lang)} else if let Some(hint) = wrapper_hint(program) {bail!("{hint}")} else {bail!(- "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java, Go, PHP, C, C++ and C#. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js (or bun app.ts, deno run -A app.ts)\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run .\n fast-anything scan -- php app.php\n fast-anything scan -- clang -O2 main.c (or gcc, g++, clang++, icpx)\n fast-anything scan -- dotnet run -c Release"+ "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java, Go, PHP, C, C++, C# and R. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js (or bun app.ts, deno run -A app.ts)\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run .\n fast-anything scan -- php app.php\n fast-anything scan -- clang -O2 main.c (or gcc, g++, clang++, icpx)\n fast-anything scan -- dotnet run -c Release\n fast-anything scan -- Rscript app.R")}}@@ -90,7 +93,15 @@ impl Lang {pub fn c_bridge(self) -> bool {matches!(self,- Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp | Lang::Kotlin+ Lang::Ruby+ | Lang::Java+ | Lang::Go+ | Lang::Php+ | Lang::C+ | Lang::Cpp+ | Lang::CSharp+ | Lang::Kotlin+ | Lang::R)}@@ -105,6 +116,7 @@ impl Lang {Lang::C => "C",Lang::Cpp => "C++",Lang::CSharp => "C#",+ Lang::R => "R",Lang::Kotlin => "Kotlin",}}@@ -119,6 +131,7 @@ impl Lang {Lang::Php => php::resolve(program, root),Lang::C | Lang::Cpp => cfamily::resolve(program, root),Lang::CSharp => csharp::resolve(program, root),+ Lang::R => r::resolve(program, root),Lang::Kotlin => java::resolve(program, root),}}@@ -133,6 +146,7 @@ impl Lang {Lang::Php => php::profile(ctx, exe, args),Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),Lang::CSharp => csharp::profile(ctx, exe, args),+ Lang::R => r::profile(ctx, exe, args),Lang::Kotlin => kotlin::profile(ctx, exe, args),}}@@ -155,6 +169,7 @@ impl Lang {Lang::Php => php::record(ctx, exe, args, hs, out, limit),Lang::C | Lang::Cpp => cfamily::record(ctx, exe, args, hs, out, self),Lang::CSharp => csharp::record(ctx, exe, args, hs, out, limit),+ Lang::R => r::record(ctx, exe, args, hs, out, limit),Lang::Kotlin => kotlin::record(ctx, exe, args, hs, out, limit),}}@@ -169,6 +184,7 @@ impl Lang {Lang::Php => php::scaffold(ctx, hs, helpers, port),Lang::C | Lang::Cpp => cfamily::scaffold(ctx, hs, helpers, port),Lang::CSharp => csharp::scaffold(ctx, hs, helpers, port),+ Lang::R => r::scaffold(ctx, hs, helpers, port),Lang::Kotlin => kotlin::scaffold(ctx, hs, helpers, port),}}@@ -183,6 +199,7 @@ impl Lang {Lang::Php => php::verify(ctx, port),Lang::C | Lang::Cpp => cfamily::verify(ctx, port),Lang::CSharp => csharp::verify(ctx, port),+ Lang::R => r::verify(ctx, port),Lang::Kotlin => kotlin::verify(ctx, port),}}@@ -197,6 +214,7 @@ impl Lang {Lang::Php => php::enable(ctx, port),Lang::C | Lang::Cpp => cfamily::enable(ctx, port),Lang::CSharp => csharp::enable(ctx, port),+ Lang::R => r::enable(ctx, port),Lang::Kotlin => kotlin::enable(ctx, port),}}@@ -211,6 +229,7 @@ impl Lang {Lang::Php => php::disable(ctx, port),Lang::C | Lang::Cpp => cfamily::disable(ctx, port),Lang::CSharp => csharp::disable(ctx, port),+ Lang::R => r::disable(ctx, port),Lang::Kotlin => kotlin::disable(ctx, port),}}@@ -241,9 +260,15 @@ impl Lang {Lang::Python => format!("{ext}.abi3.so"),Lang::Node => format!("{ext}.node"),// loaded through a C FFI (Fiddle, FFM, ...): the platform's own library name- Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp | Lang::Kotlin => {- built.clone()- }+ Lang::Ruby+ | Lang::Java+ | Lang::Go+ | Lang::Php+ | Lang::C+ | Lang::Cpp+ | Lang::CSharp+ | Lang::Kotlin+ | Lang::R => built.clone(),};(built, dest)}diff --git a/src/doctor.rs b/src/doctor.rsindex 72fc8cf..231ab83 100644--- a/src/doctor.rs+++ b/src/doctor.rs@@ -22,6 +22,7 @@ fn minimum(name: &str) -> &'static [u32] {"go" => &[1, 22],"php" => &[8, 1],"dotnet" => &[8],+ "Rscript" => &[4, 0],"bun" => &[1],"deno" => &[2],_ => &[],@@ -108,6 +109,12 @@ pub fn run() -> Result<()> {need: "for C# apps (.NET SDK 8+)",hint: "https://dot.net",},+ Check {+ name: "Rscript",+ found: version("Rscript", &["--version"]),+ need: "for R apps (4.0+)",+ hint: "https://www.r-project.org",+ },Check {name: "bun",found: version("bun", &["--version"]),@@ -153,8 +160,8 @@ pub fn run() -> Result<()> {}ensure!(usable(&checks[0]), "Rust 1.85 or newer is needed to build ports");ensure!(- checks[1..11].iter().any(usable),- "install Python, Node.js (or Bun, Deno), Ruby, Java, Go, PHP, .NET or a C compiler"+ checks[1..12].iter().any(usable),+ "install Python, Node.js (or Bun, Deno), Ruby, Java, Go, PHP, .NET, R or a C compiler");ui::ok("ready");Ok(())diff --git a/src/main.rs b/src/main.rsindex 9c5fd90..b1eac2d 100644--- a/src/main.rs+++ b/src/main.rs@@ -16,6 +16,7 @@ mod node;mod php;mod pipeline;mod python;+mod r;mod report;mod ruby;mod show;diff --git a/src/r.rs b/src/r.rsnew file mode 100644index 0000000..3a2d3f8--- /dev/null+++ b/src/r.rs@@ -0,0 +1,666 @@+//! R backend: apps run as Rscript app.R. Base R only, no R headers or libR to link: the port is+//! the same C entry point + JSON crate as Ruby's, with two extra functions R's .C() can call, and+//! its reply comes back as R source that R's own parser reads. Profiled with Rprof, recorded and+//! verified by R scripts that R loads through R_PROFILE_USER, so the app keeps its command line.++use crate::backend::{self, Profile, Recording};+use crate::hotspot::Hotspot;+use crate::native::{cargo_toml, snake};+use crate::python::DISABLE_ENV;+use crate::state::{Ctx, Port, Verify};+use crate::util::{combined, forward_slashes, output, relative, slug, tail};+use anyhow::{Context, Result, bail, ensure};+use serde_json::{Value, json};+use std::fs;+use std::path::{Path, PathBuf};+use std::process::{Command, Output, Stdio};++const RUNNER: &str = include_str!("r/runner.R");+const STARTUP: &str = include_str!("r/startup.R");+const BRIDGE: &str = include_str!("r/bridge.R");+/// R's "run as a script" check, like Python's if __name__ == "__main__".+const GUARDS: &[&str] = &["if(sys.nframe()==0)", "if(sys.nframe()==0L)", "if(0==sys.nframe())", "if(0L==sys.nframe())"];++pub fn is_r(program: &str) -> bool {+ crate::util::program_stem(program) == "rscript"+}++pub fn resolve(program: &str, root: &Path) -> Result<String> {+ let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };+ let script = "cat(file.path(R.home('bin'), if (.Platform$OS.type == 'windows') 'Rscript.exe' else 'Rscript'), \+ paste(R.version$major, R.version$minor, sep = '.'), l10n_info()[['UTF-8']], sep = '\\n')";+ let out = output(Command::new(&prog).args(["-e", script]).current_dir(root), "Rscript")?;+ ensure!(out.status.success(), "{program} failed:\n{}", tail(&combined(&out), 5));+ let text = String::from_utf8_lossy(&out.stdout).into_owned();+ let mut lines = text.lines();+ let exe = lines.next().unwrap_or_default().trim().to_string();+ let version: Vec<u32> = lines.next().unwrap_or_default().split('.').filter_map(|s| s.parse().ok()).collect();+ ensure!(version.as_slice() >= &[4, 0][..], "R 4.0 or newer is needed (found {version:?})");+ if lines.next().map(str::trim) == Some("FALSE") {+ crate::ui::warn(+ "R runs in a locale that isn't UTF-8 (see LANG), so it treats non-ASCII text byte by byte while a Rust port sees characters. Use a UTF-8 locale, e.g. LANG=C.UTF-8",+ );+ }+ Ok(exe)+}++/// The script in "Rscript [options] app.R args".+fn entry(args: &[String]) -> Result<&String> {+ for a in args {+ ensure!(+ a != "--vanilla" && a != "--no-init-file",+ "{a} stops R from loading fast-anything's startup file: leave it out while fast-anything profiles or records"+ );+ ensure!(+ a != "-e",+ "Rscript -e isn't supported; point it at a script, e.g. fast-anything scan -- Rscript app.R"+ );+ if !a.starts_with('-') {+ return Ok(a);+ }+ }+ bail!("name the script to run, e.g. fast-anything scan -- Rscript app.R")+}++fn main_guard(text: &str) -> Option<usize> {+ backend::line_starting(text, GUARDS)+}++/// A JSON value as an R literal (for the job files, so the R side needs no JSON parser).+fn r_literal(v: &Value) -> String {+ match v {+ Value::Null => "NULL".into(),+ Value::Bool(b) => (if *b { "TRUE" } else { "FALSE" }).into(),+ Value::Number(n) => n.to_string(),+ Value::String(s) => r_string(s),+ Value::Array(items) => format!("list({})", items.iter().map(r_literal).collect::<Vec<_>>().join(", ")),+ Value::Object(map) => format!(+ "list({})",+ map.iter().map(|(k, x)| format!("{} = {}", r_string(k), r_literal(x))).collect::<Vec<_>>().join(", ")+ ),+ }+}++/// An R string literal, ASCII only.+fn r_string(s: &str) -> String {+ let mut out = String::from("\"");+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c if c.is_ascii() && !c.is_ascii_control() => out.push(c),+ c => out.push_str(&format!("\\U{{{:x}}}", c as u32)),+ }+ }+ out.push('"');+ out+}++fn write_scripts(ctx: &Ctx) -> Result<()> {+ fs::write(ctx.fast.join("runner.R"), RUNNER)?;+ fs::write(ctx.fast.join("startup.R"), STARTUP)?;+ fs::write(ctx.fast.join("bridge.R"), BRIDGE)?;+ Ok(())+}++fn runner(ctx: &Ctx, rscript: &str, mode: &str, job: Value) -> Result<Output> {+ write_scripts(ctx)?;+ let job_path = ctx.fast.join(format!("job-{mode}.R"));+ fs::write(&job_path, format!("job <- {}\n", r_literal(&job)))?;+ let out = output(+ Command::new(rscript)+ .arg(ctx.fast.join("runner.R"))+ .arg(mode)+ .arg(&job_path)+ .current_dir(&ctx.root)+ .stdin(Stdio::null()),+ "Rscript",+ )?;+ if !out.status.success() {+ bail!("the R {mode} step failed ({}):\n{}", out.status, tail(&combined(&out), 30));+ }+ Ok(out)+}++/// Run the app with fast-anything's startup file loaded first (the app's own still runs after it).+fn run_app(ctx: &Ctx, rscript: &str, args: &[String], mode: &str, env: &[(&str, &Path)]) -> Result<Output> {+ write_scripts(ctx)?;+ let mut cmd = Command::new(rscript);+ cmd.args(args)+ .current_dir(&ctx.root)+ .env("R_PROFILE_USER", ctx.fast.join("startup.R"))+ .env("FAST_ANYTHING_MODE", mode)+ .env("FAST_ANYTHING_BRIDGE", ctx.fast.join("bridge.R"))+ .stdin(Stdio::null());+ if let Some(user) = std::env::var_os("R_PROFILE_USER") {+ cmd.env("FAST_ANYTHING_USER_RPROFILE", user);+ }+ for (k, v) in env {+ cmd.env(k, v);+ }+ output(&mut cmd, "Rscript")+}++pub fn profile(ctx: &Ctx, rscript: &str, args: &[String]) -> Result<Profile> {+ let script = entry(args)?.clone();+ let rprof = ctx.fast.join("Rprof.out");+ let run = run_app(ctx, rscript, args, "profile", &[("FAST_ANYTHING_OUT", &rprof)])?;+ ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));+ let result = ctx.fast.join("profile.json");+ let job = json!({ "root": ctx.root, "rprof": rprof, "entry": ctx.root.join(script), "out": result });+ runner(ctx, rscript, "report", job)?;+ serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")+}++fn wrap_line(name: &str) -> String {+ format!("if (exists(\".fast_anything_wrap\")) {name} <- .fast_anything_wrap({name})")+}++/// Record calls for one run: a line right after the definitions (appended to the file, or put+/// before the entry script's main block) hands the function to the recorder. The file is+/// restored afterwards.+pub fn record(ctx: &Ctx, rscript: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {+ entry(args)?;+ let file = ctx.root.join(&hs.file);+ let original = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;+ let backup_dir = ctx.fast.join("backup");+ fs::create_dir_all(&backup_dir)?;+ let backup = backup_dir.join(slug(&hs.file));+ fs::write(&backup, &original)?;+ let id = format!("recording {}", hs.id);+ let line = wrap_line(&hs.name);+ let patched = if hs.module.as_deref() == Some("__main__") {+ backend::insert_marked(&original, "#", &id, &line, main_guard)+ } else {+ backend::append_marked(&original, "#", &id, &line)+ };+ fs::write(&file, patched)?;+ let meta = out.with_extension("meta.json");+ let limit_text = PathBuf::from(limit.to_string());+ let run = run_app(+ ctx,+ rscript,+ args,+ "record",+ &[+ ("FAST_ANYTHING_RECORD_OUT", out),+ ("FAST_ANYTHING_RECORD_META", &meta),+ ("FAST_ANYTHING_RECORD_LIMIT", &limit_text),+ (DISABLE_ENV, Path::new("1")),+ ],+ );+ fs::write(&file, &original)+ .with_context(|| format!("restoring {} (a copy is in {})", hs.file, backup.display()))?;+ let _ = fs::remove_file(&backup);+ let run = run?;+ ensure!(run.status.success(), "the app failed while recording ({}):\n{}", run.status, tail(&combined(&run), 30));+ serde_json::from_str(&fs::read_to_string(&meta)?).context("reading the recording summary")+}++// ------------------------------------------------------------------ the crate++/// An R default value as JSON, if it's a simple literal (the R side passes every argument, so+/// this only matters for calls made from Rust).+pub fn default_json(value: &str) -> Option<String> {+ let v = value.trim();+ Some(match v {+ "NULL" | "NA" => "null".into(),+ "TRUE" | "T" => "true".into(),+ "FALSE" | "F" => "false".into(),+ _ if v.strip_suffix('L').unwrap_or(v).parse::<i64>().is_ok() => v.trim_end_matches('L').into(),+ _ if v.parse::<f64>().is_ok() => v.into(),+ _ if v.len() >= 2+ && ((v.starts_with('"') && v.ends_with('"')) || (v.starts_with('\'') && v.ends_with('\''))) =>+ {+ serde_json::to_string(&v[1..v.len() - 1]).ok()?+ }+ _ => return None,+ })+}++/// What R's .C() calls, and the r module ports use: generated next to the shared glue.+const R_GLUE: &str = r#"+// ------------------------------------------------------------------ R++/// Types for R values. R has no scalars (a length-1 vector arrives as a plain value), NA arrives+/// as null, and NaN / Inf / -Inf, which JSON has no numbers for, as {"$num": "NaN" | "Inf" | "-Inf"}.+#[allow(dead_code)]+pub mod r {+ use serde::de::{self, Deserialize, Deserializer};+ use serde::ser::{Serialize, SerializeMap, Serializer};++ /// A number that may be NaN or +-Inf (NA is null: use Option<Num>).+ #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]+ pub struct Num(pub f64);++ impl<'de> Deserialize<'de> for Num {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ #[derive(serde::Deserialize)]+ #[serde(untagged)]+ enum Repr {+ Plain(f64),+ Tagged {+ #[serde(rename = "$num")]+ num: String,+ },+ }+ match Repr::deserialize(d)? {+ Repr::Plain(x) => Ok(Num(x)),+ Repr::Tagged { num } => match num.as_str() {+ "NaN" => Ok(Num(f64::NAN)),+ "Inf" => Ok(Num(f64::INFINITY)),+ "-Inf" => Ok(Num(f64::NEG_INFINITY)),+ other => Err(de::Error::custom(format!("not a number: {other}"))),+ },+ }+ }+ }++ impl Serialize for Num {+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ if self.0.is_finite() {+ return s.serialize_f64(self.0);+ }+ let mut map = s.serialize_map(Some(1))?;+ map.serialize_entry("$num", if self.0.is_nan() { "NaN" } else if self.0 > 0.0 { "Inf" } else { "-Inf" })?;+ map.end()+ }+ }++ /// A vector argument: an array, or the plain value a length-1 vector arrives as.+ #[derive(Debug, Clone, PartialEq, Default)]+ pub struct Vector<T>(pub Vec<T>);++ impl<'de, T: Deserialize<'de>> Deserialize<'de> for Vector<T> {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ #[derive(serde::Deserialize)]+ #[serde(untagged)]+ enum Repr<T> {+ Many(Vec<T>),+ One(T),+ }+ Ok(match Repr::deserialize(d)? {+ Repr::Many(v) => Vector(v),+ Repr::One(x) => Vector(vec![x]),+ })+ }+ }++ impl<T: Serialize> Serialize for Vector<T> {+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ s.collect_seq(&self.0)+ }+ }++ impl<T> std::ops::Deref for Vector<T> {+ type Target = Vec<T>;+ fn deref(&self) -> &Vec<T> {+ &self.0+ }+ }++ /// R's NULL as a result (None, like null anywhere, is NA).+ pub struct Null;++ impl Serialize for Null {+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ let mut map = s.serialize_map(Some(1))?;+ map.serialize_entry("$null", &true)?;+ map.end()+ }+ }++ /// A result that must be an R list. Without it, an array of plain values becomes a vector+ /// (c(...)), and an object whose values are all plain becomes a named vector.+ pub struct List<T>(pub T);++ impl<T: Serialize> Serialize for List<T> {+ fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {+ let mut map = s.serialize_map(Some(1))?;+ map.serialize_entry("$list", &self.0)?;+ map.end()+ }+ }++ pub(crate) fn string(s: &str) -> String {+ let mut out = String::from("\"");+ for c in s.chars() {+ match c {+ '"' => out.push_str("\\\""),+ '\\' => out.push_str("\\\\"),+ '\n' => out.push_str("\\n"),+ '\r' => out.push_str("\\r"),+ '\t' => out.push_str("\\t"),+ c if c.is_ascii() && !c.is_ascii_control() => out.push(c),+ c => out.push_str(&format!("\\U{{{:x}}}", c as u32)),+ }+ }+ out.push('"');+ out+ }++ fn special(v: &serde_json::Value) -> Option<&str> {+ v.as_object().filter(|m| m.len() == 1)?.get("$num")?.as_str()+ }++ fn plain(v: &serde_json::Value) -> bool {+ !v.is_array() && !v.is_object() || special(v).is_some()+ }++ fn named(map: &serde_json::Map<String, serde_json::Value>, item: fn(&serde_json::Value) -> String) -> String {+ map.iter().map(|(k, x)| format!("{} = {}", string(k), item(x))).collect::<Vec<_>>().join(", ")+ }++ fn element(v: &serde_json::Value) -> String {+ if v.is_null() { "NULL".into() } else { source(v) }+ }++ fn list(v: &serde_json::Value) -> String {+ match v {+ serde_json::Value::Array(items) => {+ format!("list({})", items.iter().map(element).collect::<Vec<_>>().join(", "))+ }+ serde_json::Value::Object(map) => format!("list({})", named(map, element)),+ other => format!("list({})", element(other)),+ }+ }++ /// A value as R source.+ pub(crate) fn source(v: &serde_json::Value) -> String {+ use serde_json::Value;+ match v {+ Value::Null => "NA".into(),+ Value::Bool(b) => (if *b { "TRUE" } else { "FALSE" }).into(),+ Value::Number(n) => match n.as_i64() {+ Some(i) => i.to_string(),+ None => format!("{:?}", n.as_f64().unwrap_or(f64::NAN)),+ },+ Value::String(s) => string(s),+ Value::Array(items) if items.is_empty() => "logical(0)".into(),+ Value::Array(items) if items.iter().all(plain) => {+ format!("c({})", items.iter().map(source).collect::<Vec<_>>().join(", "))+ }+ Value::Array(_) => list(v),+ Value::Object(map) if map.len() == 1 && map.contains_key("$null") => "NULL".into(),+ Value::Object(map) => match (special(v), map.get("$list")) {+ (Some("NaN"), _) => "NaN".into(),+ (Some("Inf"), _) => "Inf".into(),+ (Some("-Inf"), _) => "-Inf".into(),+ (_, Some(inner)) if map.len() == 1 => list(inner),+ _ if map.is_empty() => "list()".into(),+ _ if map.values().all(plain) => format!("c({})", named(map, source)),+ _ => list(v),+ },+ }+ }+}++thread_local! {+ static FA_R_REPLY: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };+}++/// R's .C("fa_r_call", json, n = integer(1)): runs the port and keeps its reply (R source for+/// list(ok = ...) or list(error = "...")) for fa_r_take; n is its length in bytes.+///+/// # Safety+/// input must point to one NUL-terminated string and len to an int, as .C() passes them.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn fa_r_call(input: *const *const std::ffi::c_char, len: *mut i32) {+ let bytes = unsafe { std::ffi::CStr::from_ptr(*input) }.to_bytes();+ let reply = match std::panic::catch_unwind(|| call(bytes)) {+ Ok(Ok(value)) => format!("list(ok = {})", r::source(&value)),+ Ok(Err(message)) => format!("list(error = {})", r::string(&message)),+ Err(panic) => {+ let text = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());+ format!("list(error = {})", r::string(&format!("panic: {}", text.unwrap_or_default())))+ }+ };+ unsafe { *len = reply.len() as i32 };+ FA_R_REPLY.with(|r| *r.borrow_mut() = reply.into_bytes());+}++/// R's .C("fa_r_take", strrep(" ", n)): copies the reply into that string.+///+/// # Safety+/// out must point to a writable string of at least the length fa_r_call reported.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn fa_r_take(out: *mut *mut std::ffi::c_char) {+ FA_R_REPLY.with(|r| {+ let reply = r.borrow();+ unsafe { std::ptr::copy_nonoverlapping(reply.as_ptr(), *out as *mut u8, reply.len()) };+ });+}+"#;++pub fn port_rs(hs: &Hotspot, port: &Port) -> String {+ let params: Vec<String> = hs.params.iter().map(|p| format!("{}: serde_json::Value", snake(&p.name))).collect();+ format!(+ "//! Rust port of {id} ({file}:{line}), generated by fast-anything.\n\+ //! Replace the todo!() with a faithful, fast port, and the serde_json::Value types with real ones\n\+ //! (TASK.md says how R values arrive). Return Err(message) where R would stop().\n\+ //! Check it with: fast-anything verify {id}\n\n\+ #[allow(unused_imports)]\n\+ use crate::r::{{List, Null, Num, Vector}};\n\n\+ #[allow(unused_variables)]\n\+ pub fn {func}({params}) -> Result<serde_json::Value, String> {{\n todo!(\"port {id}\")\n}}\n",+ id = port.id,+ file = hs.file,+ line = hs.line,+ func = snake(&hs.name),+ params = params.join(", "),+ )+}++fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {+ let Ok(text) = fs::read_to_string(path) else { return vec![] };+ let clip = |s: String, n: usize| {+ if s.chars().count() <= n { s } else { format!("{}…", s.chars().take(n - 1).collect::<String>()) }+ };+ text.lines()+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())+ .take(n)+ .map(|case| {+ let args: Vec<String> =+ case["args"].as_array().map(|a| a.iter().map(|v| v.to_string()).collect()).unwrap_or_default();+ let outcome = match case.get("raises") {+ Some(e) => format!("stops ({})", e.as_str().unwrap_or("error")),+ None => case["result"].to_string(),+ };+ format!("{} -> {}", clip(format!("{func}({})", args.join(", ")), 110), clip(outcome, 60))+ })+ .collect()+}++pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {+ let fence = "```";+ let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");+ let mut helper_md = String::new();+ if !hs.calls.is_empty() {+ helper_md.push_str("## Helpers it calls\n\nPort these as private Rust functions in src/port.rs (they stay in R for everyone else).\n\n");+ for name in &hs.calls {+ match helpers.iter().find(|h| &h.name == name) {+ Some(h) => helper_md.push_str(&format!("{fence}r\n{}\n{fence}\n\n", h.source)),+ None => helper_md.push_str(&format!("- `{name}`: read it in {}\n", hs.file)),+ }+ }+ }+ format!(+ "# Port `{id}` to Rust\n\n\+You're in a Rust crate fast-anything generated for this: `{dir}`.\n\+Write `{func}` in `src/port.rs` so it behaves **exactly** like the R below, and runs fast.\n\+`src/lib.rs` is generated glue (JSON in, R values out, through a C entry point): don't edit it.\n\+Only edit files in this folder. Don't touch the R project.\n\n\+## The original ({file}:{line})\n\n{fence}r\n{source}\n{fence}\n\n\+{helper_md}\+## Real calls\n\n\+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON, in parameter order. A few:\n\n{fence}\n{samples}\n{fence}\n\n\+## How R values arrive and go back\n\n\+- R has no scalars: a length-1 vector arrives as a plain value, a longer one as an array. Take vectors as `Vector<T>` (`crate::r::Vector`, accepts both; derefs to `Vec<T>`).\n\+- Integer and double vectors both arrive as numbers; take `f64` (or `i64` when the R code only uses whole numbers). NA arrives as null: `Option<T>`.\n\+- NaN, Inf and -Inf arrive as `{{\"$num\": \"NaN\"}}` etc.: take `Num` (`crate::r::Num`, a wrapped f64) where they can occur, and return `Num` to give them back.\n\+- Named vectors and named lists arrive as objects (`HashMap<String, _>` or a struct); unnamed lists as arrays.\n\+- The result goes back as R values: a number or string becomes a length-1 vector, an array of plain values a vector (`c(...)`), an object of plain values a named vector, anything nested a list. Wrap it in `List(...)` (`crate::r::List`) when R returns a list; `None` is NA, and `Null` is R's NULL.\n\+- Integer vs double doesn't matter to verify (R prints them alike); names, NA and list structure do. Where R stops with an error, return `Err(message)`.\n\n\+## Rules\n\n\+- Same result for every input, edge cases included: empty vectors, zero, negatives, NA, non-ASCII text, very long input. verify tests these too.\n\+- R strings index by character: use `.chars()` (or bytes only after checking `is_ascii()`). R indexes from 1.\n\+- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases.\n\+- Keep the function name.\n\n\+## Check\n\n\+Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all recorded calls against it\n\+(`fast-anything verify {id}`).\n",+ id = port.id,+ dir = crate_dir.display(),+ func = hs.name,+ file = hs.file,+ line = hs.line,+ source = hs.source,+ recorded = port.recorded,+ seen = crate::util::thousands(port.calls_seen),+ )+}++pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {+ let dir = ctx.crate_dir(port);+ fs::create_dir_all(dir.join("src"))?;+ fs::create_dir_all(dir.join(".cargo"))?;+ fs::write(dir.join("Cargo.toml"), cargo_toml(port))?;+ fs::write(dir.join(".cargo/config.toml"), backend::CARGO_CONFIG)?;+ fs::write(dir.join("src/lib.rs"), crate::native::glue_rs(hs, port, default_json) + R_GLUE)?;+ let body = dir.join("src/port.rs");+ if !body.exists() {+ fs::write(&body, port_rs(hs, port))?;+ }+ let task = task_md(hs, helpers, port, &dir);+ fs::write(dir.join("TASK.md"), &task)?;+ Ok(task)+}++pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {+ let rscript = ctx.runtime()?;+ let dir = ctx.crate_dir(port);+ let out = dir.join("verify.json");+ let (_, lib) = backend::Lang::R.artifact(&port.ext);+ let job = json!({+ "root": ctx.root, "lib": ctx.lib_dir().join(lib), "func": port.func,+ "module_file": ctx.root.join(&port.file), "cases": dir.join("recordings.rds"), "out": out, "budget": 0.5,+ });+ runner(ctx, rscript, "verify", job)?;+ let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;+ v.built = true;+ Ok(v)+}++// ------------------------------------------------------------------ the shim++/// R has no reliable "this file's folder": the shim looks for the port next to the file it was+/// sourced from (or the Rscript script), then where the project was when it was enabled.+pub fn shim(port: &Port, lib_rel: &str, lib_abs: &str) -> String {+ let f = &port.func;+ [+ "# Uses the verified Rust port. FAST_ANYTHING_DISABLE=1 runs the R above instead.".to_string(),+ format!("# Undo with: fast-anything disable {}", port.id),+ format!("if (!nzchar(Sys.getenv(\"FAST_ANYTHING_DISABLE\"))) {f} <- local({{"),+ " from <- c(tryCatch(dirname(normalizePath(sys.frame(1)$ofile)), error = function(e) NULL),".to_string(),+ " tryCatch(dirname(normalizePath(sub(\"^--file=\", \"\", grep(\"^--file=\", commandArgs(FALSE), value = TRUE)[1]))), error = function(e) NULL))".to_string(),+ format!(" libs <- c(file.path(from, {}), {})", r_string(lib_rel), r_string(lib_abs)),+ " lib <- libs[file.exists(libs)][1]".to_string(),+ format!(" if (is.na(lib)) {f} else tryCatch({{"),+ " fa <- new.env()".to_string(),+ " sys.source(file.path(dirname(lib), \"fast_anything.R\"), envir = fa)".to_string(),+ format!(" fa$.fa_port(lib, {f})"),+ format!(" }}, error = function(e) {f})"),+ "})".to_string(),+ ]+ .join("\n")+}++pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {+ let file = ctx.root.join(&port.file);+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;+ let from = file.parent().context("file has no folder")?;+ let (_, lib) = backend::Lang::R.artifact(&port.ext);+ let lib_path = ctx.lib_dir().join(lib);+ fs::write(ctx.lib_dir().join("fast_anything.R"), BRIDGE)?;+ let rel = forward_slashes(&relative(from, &lib_path));+ let abs = forward_slashes(&lib_path);+ let block = shim(port, &rel, &abs);+ let patched = if port.module == "__main__" {+ backend::insert_marked(&text, "#", &port.id, &block, main_guard)+ } else {+ backend::append_marked(&text, "#", &port.id, &block)+ };+ fs::write(&file, patched).with_context(|| format!("writing {}", port.file))+}++pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {+ let file = ctx.root.join(&port.file);+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;+ fs::write(&file, backend::strip_marked(&text, "#", &port.id)).with_context(|| format!("writing {}", port.file))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn spots_r_and_its_script() {+ assert!(is_r("Rscript") && is_r("/usr/bin/Rscript") && is_r("C:\\R\\bin\\Rscript.exe") && !is_r("R"));+ let args = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();+ assert_eq!(entry(&args("--no-save app.R data.csv")).unwrap(), "app.R");+ assert!(entry(&args("--vanilla app.R")).unwrap_err().to_string().contains("startup file"));+ assert!(entry(&args("-e 1")).is_err());+ assert_eq!(main_guard("f <- function(x) x\n\nif (sys.nframe() == 0) {\n main()\n}\n"), Some(20));+ }++ #[test]+ fn bridge_encodes_and_compares_like_r() {+ if !Command::new("Rscript").arg("--version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no Rscript on PATH, skipping");+ return;+ }+ let bridge = std::env::temp_dir().join(format!("fa-bridge-test-{}.R", std::process::id()));+ fs::write(&bridge, BRIDGE).unwrap();+ let check = r#"+ fa <- new.env(); sys.source(commandArgs(TRUE)[1], envir = fa)+ stopifnot(+ fa$.fa_json(2) == "2", fa$.fa_json(c(1.5, 2)) == "[1.5,2]", fa$.fa_json(0.1) == "0.1",+ fa$.fa_json(5L) == "5", fa$.fa_json(c(TRUE, NA)) == "[true,null]", fa$.fa_json(NULL) == "null",+ fa$.fa_json(c(NaN, Inf, -Inf)) == '[{"$num":"NaN"},{"$num":"Inf"},{"$num":"-Inf"}]',+ fa$.fa_json(c(a = 1, b = 2)) == '{"a":1,"b":2}', fa$.fa_json(character(0)) == "[]",+ fa$.fa_json(list(1, "x\n\"")) == '[1,"x\\n\\""]', fa$.fa_json("\u00e9") == '"\u00e9"',+ fa$.fa_json(list(a = list(1, 2))) == '{"a":[1,2]}'+ )+ stopifnot(inherits(tryCatch(fa$.fa_json(factor("a")), error = function(e) e), "fa_unsupported"))+ stopifnot(+ fa$.fa_same(5L, 5), fa$.fa_same(c(a = 1), c(a = 1 + 1e-12)), !fa$.fa_same(c(a = 1), c(b = 1)),+ fa$.fa_same(NA_real_, NA), fa$.fa_same(NA_character_, NA), !fa$.fa_same(NA, 1),+ fa$.fa_same(Inf, Inf), !fa$.fa_same(Inf, -Inf), fa$.fa_same(character(0), NULL),+ !fa$.fa_same(list(1), 1), fa$.fa_same(list(c(1L, 2L)), list(c(1, 2))), !fa$.fa_same("a", "b")+ )+ "#;+ let script = bridge.with_extension("check.R");+ fs::write(&script, check).unwrap();+ let out = Command::new("Rscript").arg(&script).arg(&bridge).output().unwrap();+ let _ = fs::remove_file(&bridge);+ let _ = fs::remove_file(&script);+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ }++ #[test]+ fn r_literals() {+ assert_eq!(r_string("a\"b\\\n\u{e9}"), "\"a\\\"b\\\\\\n\\U{e9}\"");+ assert_eq!(+ r_literal(&json!({ "lib": "C:\\x", "n": 2, "on": true, "none": null, "xs": [1, "a"] })),+ "list(\"lib\" = \"C:\\\\x\", \"n\" = 2, \"none\" = NULL, \"on\" = TRUE, \"xs\" = list(1, \"a\"))"+ );+ assert_eq!(default_json("2L").as_deref(), Some("2"));+ assert_eq!(default_json("TRUE").as_deref(), Some("true"));+ assert_eq!(default_json("NA").as_deref(), Some("null"));+ assert_eq!(default_json("'a'").as_deref(), Some("\"a\""));+ assert_eq!(default_json("c(1, 2)"), None);+ }+}diff --git a/src/r/bridge.R b/src/r/bridge.Rnew file mode 100644index 0000000..da9af22--- /dev/null+++ b/src/r/bridge.R@@ -0,0 +1,126 @@+# fast-anything's R bridge: R values to JSON for a Rust port, the port's reply back to R values,+# and the comparison verify uses. Base R only. Copied into <project>/.fast; not meant to be used+# by hand.++.fa_unsupported <- function(x) {+ stop(structure(class = c("fa_unsupported", "error", "condition"),+ list(message = class(x)[1], call = NULL)))+}++# JSON string literals for a character vector without NAs+.fa_str <- function(s) {+ s <- enc2utf8(as.character(s))+ s <- gsub("\\", "\\\\", s, fixed = TRUE)+ s <- gsub("\"", "\\\"", s, fixed = TRUE)+ s <- gsub("\n", "\\n", s, fixed = TRUE)+ s <- gsub("\r", "\\r", s, fixed = TRUE)+ s <- gsub("\t", "\\t", s, fixed = TRUE)+ ctrl <- grepl("[\001-\037]", s, useBytes = TRUE)+ if (any(ctrl)) {+ s[ctrl] <- vapply(s[ctrl], function(one) {+ codes <- utf8ToInt(one)+ paste(ifelse(codes < 32, sprintf("\\u%04x", codes), vapply(codes, intToUtf8, "")), collapse = "")+ }, "", USE.NAMES = FALSE)+ }+ paste0("\"", s, "\"")+}++# JSON tokens for a double vector. NA is null; NaN and +-Inf, which JSON has no numbers for, are+# {"$num": ...} (the port reads them with r::Num).+.fa_num <- function(x) {+ out <- sprintf("%.15g", x)+ ok <- is.finite(x)+ inexact <- ok & suppressWarnings(as.numeric(out)) != x+ out[which(inexact)] <- sprintf("%.17g", x[which(inexact)])+ out[is.na(x) & !is.nan(x)] <- "null"+ out[is.nan(x)] <- "{\"$num\":\"NaN\"}"+ out[!is.na(x) & x == Inf] <- "{\"$num\":\"Inf\"}"+ out[!is.na(x) & x == -Inf] <- "{\"$num\":\"-Inf\"}"+ out+}++# An R value as JSON: a length-1 vector is a plain value, a longer one an array, a named one an+# object; lists likewise. Anything with other attributes (factors, data frames, dates...) or of+# another type is unsupported.+.fa_json <- function(x) {+ if (is.null(x)) return("null")+ if (length(setdiff(names(attributes(x)), "names"))) .fa_unsupported(x)+ keys <- names(x)+ if (is.list(x)) {+ parts <- vapply(x, .fa_json, "", USE.NAMES = FALSE)+ if (!is.null(keys)) return(paste0("{", paste0(.fa_str(keys), ":", parts, collapse = ","), "}"))+ return(paste0("[", paste(parts, collapse = ","), "]"))+ }+ parts <- switch(typeof(x),+ double = .fa_num(x),+ integer = ifelse(is.na(x), "null", as.character(x)),+ logical = ifelse(is.na(x), "null", ifelse(x, "true", "false")),+ character = ifelse(is.na(x), "null", .fa_str(ifelse(is.na(x), "", x))),+ .fa_unsupported(x))+ if (!is.null(keys)) return(paste0("{", paste0(.fa_str(keys), ":", parts, collapse = ","), "}"))+ if (length(x) == 1L) return(parts)+ paste0("[", paste(parts, collapse = ","), "]")+}++.fa_load <- function(lib) {+ dll <- dyn.load(lib)+ list(call = getNativeSymbolInfo("fa_r_call", dll), take = getNativeSymbolInfo("fa_r_take", dll))+}++# Call the port with a list of arguments (in the original's parameter order). Its reply comes back+# as R source (c(...), list(...), NA, Inf...), which R's own parser reads.+.fa_invoke <- function(port, args) {+ input <- paste0("[", paste(vapply(args, .fa_json, "", USE.NAMES = FALSE), collapse = ","), "]")+ n <- .C(port$call, input, n = integer(1))$n+ reply <- eval(parse(text = .C(port$take, out = strrep(" ", n))$out, keep.source = FALSE), baseenv())+ if (!is.null(reply$error)) stop(reply$error, call. = FALSE)+ reply$ok+}++# A function with the original's parameters (and defaults) that calls `run` with the argument+# values, in parameter order.+.fa_like <- function(original, run) {+ g <- function() NULL+ formals(g) <- formals(original)+ body(g) <- substitute(RUN(mget(names(formals(sys.function())), envir = environment())), list(RUN = run))+ environment(g) <- environment(original)+ g+}++# The Rust port in place of `original`.+.fa_port <- function(lib, original) {+ port <- .fa_load(lib)+ invoke <- .fa_invoke+ .fa_like(original, function(args) invoke(port, unname(args)))+}++# Same result the way R code sees it: integer and double are both numbers, doubles within 1e-9,+# NA where NA, zero-length vectors and NULL alike, names and list structure must match.+.fa_same <- function(a, b) {+ if (length(a) == 0L && length(b) == 0L && !is.list(a) && !is.list(b)) return(TRUE)+ if (is.list(a) || is.list(b)) {+ if (!(is.list(a) && is.list(b)) || length(a) != length(b) || !identical(names(a), names(b))) return(FALSE)+ return(all(mapply(.fa_same, a, b)))+ }+ if (length(a) != length(b) || !identical(names(a), names(b))) return(FALSE)+ # an NA from Rust has no type; R turns logical NA into any other type where needed+ if ((is.logical(a) && all(is.na(a))) || (is.logical(b) && all(is.na(b)))) {+ return(all(is.na(a)) && all(is.na(b)))+ }+ if (is.numeric(a) && is.numeric(b)) {+ if (!identical(is.na(a), is.na(b)) || !identical(is.nan(a), is.nan(b))) return(FALSE)+ a <- as.double(a[!is.na(a)])+ b <- as.double(b[!is.na(b)])+ inf <- is.infinite(a) | is.infinite(b)+ if (!identical(a[inf], b[inf])) return(FALSE)+ a <- a[!inf]+ b <- b[!inf]+ return(all(a == b | abs(a - b) <= pmax(1e-12, 1e-9 * pmax(abs(a), abs(b)))))+ }+ identical(typeof(a), typeof(b)) && identical(unname(a), unname(b))+}++.fa_show <- function(x, limit = 160L) {+ text <- paste(deparse(x, width.cutoff = 500L, nlines = 3L), collapse = " ")+ if (nchar(text) > limit) paste0(substr(text, 1L, limit - 1L), "\u2026") else text+}diff --git a/src/r/runner.R b/src/r/runner.Rnew file mode 100644index 0000000..cfafc5a--- /dev/null+++ b/src/r/runner.R@@ -0,0 +1,289 @@+# fast-anything's R side. The CLI copies this file to <project>/.fast/runner.R and runs it as+# Rscript runner.R <mode> <job.R>+# where job.R sets `job`. Modes: report (Rprof output -> profile.json), verify. Base R only; not+# meant to be run by hand.++args <- commandArgs(trailingOnly = TRUE)+mode <- args[[1]]+job <- local({ env <- new.env(); sys.source(args[[2]], envir = env); env$job })+here <- dirname(normalizePath(sub("^--file=", "", grep("^--file=", commandArgs(FALSE), value = TRUE)[1])))+fa <- new.env()+sys.source(file.path(here, "bridge.R"), envir = fa)++# ------------------------------------------------------------------ static analysis++SKIP_DIRS <- c(".fast", ".git", "renv", "packrat", "node_modules")+IO <- c("cat", "print", "message", "warning", "writeLines", "readLines", "readline", "readRDS", "saveRDS",+ "load", "save", "file", "url", "download.file", "read.csv", "read.table", "read.delim", "write.csv",+ "write.table", "sink", "system", "system2", "Sys.sleep", "scan", "source", "sys.source", "library",+ "require", "requireNamespace", "Sys.setenv", "setwd", "dir.create", "unlink", "file.remove")+NONDET <- c("runif", "rnorm", "rbinom", "rpois", "rexp", "sample", "sample.int", "set.seed", "Sys.time",+ "Sys.Date", "proc.time", "date", "Sys.getpid", "tempfile")+SELF <- c("missing", "sys.call", "sys.function", "match.call", "parent.frame", "sys.frame", "sys.frames",+ "environment", "substitute", "eval", "evalq", "match.arg", "on.exit", "nargs")+GUARDS <- c("sys.nframe() == 0", "sys.nframe() == 0L", "0 == sys.nframe()", "0L == sys.nframe()")++# names of the functions a piece of code calls+calls_in <- function(code) {+ out <- character()+ walk <- function(x) {+ if (is.call(x)) {+ f <- x[[1]]+ if (is.symbol(f)) out <<- c(out, as.character(f))+ if (is.call(f) && as.character(f[[1]]) %in% c("::", ":::")) out <<- c(out, as.character(f[[3]]))+ parts <- as.list(x)+ for (k in seq_along(parts)) {+ # an empty argument (m[, 1]) is the missing-argument symbol, which can't be passed on+ if (is.symbol(parts[[k]]) && !nzchar(as.character(parts[[k]]))) next+ walk(parts[[k]])+ }+ }+ }+ walk(code)+ unique(out)+}++is_definition <- function(e) {+ is.call(e) && as.character(e[[1]])[1] %in% c("<-", "=") && is.symbol(e[[2]]) &&+ is.call(e[[3]]) && identical(e[[3]][[1]], as.name("function"))+}++# every top-level function definition in a file: name -> details+describe_file <- function(path, rel, is_entry) {+ exprs <- tryCatch(parse(path, keep.source = TRUE, encoding = "UTF-8"), error = function(e) NULL)+ if (is.null(exprs)) return(list())+ refs <- attr(exprs, "srcref")+ guard <- NA+ for (i in seq_along(exprs)) {+ e <- exprs[[i]]+ if (is.call(e) && identical(e[[1]], as.name("if")) && paste(deparse(e[[2]]), collapse = "") %in% GUARDS) {+ guard <- refs[[i]][1]+ break+ }+ }+ top <- vapply(exprs, function(e) if (is_definition(e)) as.character(e[[2]]) else "", "")+ module <- if (is_entry) "__main__" else gsub("/", ".", sub("\\.[Rr]$", "", rel))+ out <- list()+ for (i in seq_along(exprs)) {+ e <- exprs[[i]]+ if (!is_definition(e)) next+ name <- as.character(e[[2]])+ fun <- e[[3]]+ params <- as.list(fun[[2]])+ used <- calls_in(fun[[3]])+ defaults <- lapply(seq_along(params), function(k) {+ d <- paste(deparse(params[[k]]), collapse = " ") # "" for a parameter without a default+ if (nzchar(d)) d else NULL+ })+ blockers <- character()+ warnings <- character()+ if (is_entry && is.na(guard)) {+ blockers <- c(blockers, "lives in the entry script, which runs when sourced: put its main code under if (sys.nframe() == 0)")+ } else if (is_entry && refs[[i]][1] > guard) {+ blockers <- c(blockers, "defined inside or after the if (sys.nframe() == 0) block")+ }+ if ("..." %in% names(params)) blockers <- c(blockers, "takes ...")+ io <- intersect(used, IO)+ if (length(io)) blockers <- c(blockers, paste("does I/O:", paste(head(io, 3), collapse = ", ")))+ nondet <- intersect(used, NONDET)+ if (length(nondet)) blockers <- c(blockers, paste("not deterministic:", paste(head(nondet, 3), collapse = ", ")))+ if (any(c("<<-", "assign") %in% used)) blockers <- c(blockers, "writes global state")+ self <- intersect(used, SELF)+ if (length(self)) blockers <- c(blockers, paste("inspects its own call:", paste(head(self, 3), collapse = ", ")))+ helpers <- setdiff(intersect(used, top[nzchar(top)]), name)+ if (length(helpers)) warnings <- c(warnings, paste("calls", paste(head(helpers, 3), collapse = ", "), "- they get ported together with it"))+ warnings <- c(warnings, "R has no type annotations, types are inferred from recorded calls")+ ref <- refs[[i]]+ out[[length(out) + 1L]] <- list(+ qualname = name, module = module, kind = "function", owner = NULL,+ file = rel, line = ref[1], end_line = ref[3], name = name,+ params = unname(Map(function(n, d) list(name = n, annotation = NULL, default = d), names(params), defaults)),+ returns = NULL, blockers = as.list(blockers), warnings = as.list(warnings),+ portability = if (length(blockers)) 0 else 0.9, calls = as.list(helpers),+ source = paste(as.character(ref), collapse = "\n"))+ }+ out+}++project_files <- function(root) {+ files <- list.files(root, pattern = "\\.[Rr]$", recursive = TRUE, all.files = FALSE)+ files[!vapply(strsplit(files, "/", fixed = TRUE), function(p) any(head(p, -1) %in% SKIP_DIRS), TRUE)]+}++# ------------------------------------------------------------------ report++if (mode == "report") {+ wall <- as.numeric(readLines(paste0(job$rprof, ".wall")))+ times <- tryCatch(utils::summaryRprof(job$rprof)$by.total, error = function(e) NULL)+ functions <- list()+ if (!is.null(times) && nrow(times)) {+ hot <- gsub("\"", "", rownames(times), fixed = TRUE)+ entry <- if (nzchar(job$entry)) normalizePath(job$entry) else ""+ for (rel in project_files(job$root)) {+ path <- normalizePath(file.path(job$root, rel))+ for (def in describe_file(path, rel, identical(path, entry))) {+ row <- match(def$name, hot)+ if (is.na(row)) next+ def$ncalls <- 0+ def$tottime <- times$self.time[row]+ def$cumtime <- times$total.time[row]+ functions[[length(functions) + 1L]] <- def+ }+ }+ }+ writeLines(fa$.fa_json(list(wall = wall, base = ".", functions = functions)), job$out, useBytes = TRUE)+}++# ------------------------------------------------------------------ verify++seed <- 64087+random <- function(n) { # 0..n-1, our own generator+ seed <<- (seed * 69069 + 1) %% 4294967296+ floor(seed / 4294967296 * n)+}++NON_ASCII <- c("\u00e9", "\u65e5\u672c", "\U0001f44d\U0001f3fd", "e\u0301")++# inputs where ports and originals tend to part ways, of the same type as the recorded value+edges <- function(v) {+ if (!is.atomic(v) || is.null(v)) return(list())+ if (length(v) == 1L) {+ return(switch(typeof(v),+ double = Filter(function(x) !identical(x, v), list(0, 1, -1, NA_real_)),+ integer = Filter(function(x) !identical(x, v), list(0L, 1L, -1L, NA_integer_)),+ logical = list(NA),+ character = list(paste0(substr(v, 1, nchar(v) %/% 2), NON_ASCII[1], substring(v, nchar(v) %/% 2 + 1)),+ paste0(v, NON_ASCII[2]), paste0(NON_ASCII[3], v), paste0(v, NON_ASCII[4]), "", NA_character_),+ list()))+ }+ out <- list(v[0])+ for (e in edges(v[1])) {+ w <- v+ w[1] <- e+ out[[length(out) + 1L]] <- w+ }+ out+}++# a short version of a recorded value, so edge cases stay cheap when the real inputs are big+small <- function(v) {+ if (is.character(v) && length(v) == 1L && !is.na(v)) return(substr(v, 1, 64))+ if ((is.atomic(v) || is.list(v)) && length(v) > 8L) return(v[1:8])+ v+}++variants <- function(v) {+ if (!(is.atomic(v) || is.list(v)) || length(v) < 2L) return(list())+ out <- list()+ for (n in c(0, 1, 2, 3, 5, 8, 13, 21, 34, 55)) {+ if (n >= length(v)) break+ for (k in seq_len(if (n < 2) 1 else 3)) {+ start <- random(length(v) - n + 1)+ out[[length(out) + 1L]] <- v[seq_len(n) + start]+ }+ }+ out+}++if (mode == "verify") {+ Sys.setenv(FAST_ANYTHING_DISABLE = "1") # the original R, even if the port is switched on+ env <- new.env(parent = globalenv())+ sys.source(job$module_file, envir = env, keep.source = FALSE)+ original <- get(job$func, envir = env)+ port <- fa$.fa_port(job$lib, original)+ cases <- readRDS(job$cases)+ recorded <- length(cases)++ derived <- list()+ seen <- character()+ start <- proc.time()[["elapsed"]]+ budget <- 1.5 # edge cases first, then shrunk inputs, 1.5 s each+ try_case <- function(args, kind) {+ if (proc.time()[["elapsed"]] - start > budget || length(derived) >= 300) return(invisible())+ key <- tryCatch(fa$.fa_json(unname(args)), error = function(e) NULL)+ if (is.null(key) || key %in% seen) return(invisible())+ seen <<- c(seen, key)+ result <- tryCatch(do.call(original, args), error = function(e) e)+ if (inherits(result, "error") || is.null(tryCatch(fa$.fa_json(result), error = function(e) NULL))) return(invisible())+ derived[[length(derived) + 1L]] <<- list(args = args, result = result, derived = kind)+ }+ plain <- Filter(function(c) is.null(c$raises), cases)+ for (case in head(plain, 20)) {+ base <- lapply(case$args, small)+ for (i in seq_along(base)) {+ for (e in edges(base[[i]])) {+ args <- base+ args[i] <- list(e)+ try_case(args, "edge")+ }+ }+ }+ budget <- proc.time()[["elapsed"]] - start + 1.5+ for (case in plain) {+ for (i in seq_along(case$args)) {+ for (smaller in variants(case$args[[i]])) {+ args <- case$args+ args[i] <- list(smaller)+ try_case(args, "derived")+ }+ }+ }+ cases <- c(cases, derived)++ failures <- list()+ passed <- 0+ for (i in seq_along(cases)) {+ case <- cases[[i]]+ got <- tryCatch(do.call(port, case$args), error = function(e) e)+ failed <- inherits(got, "error")+ if (!is.null(case$raises)) {+ ok <- failed+ expected <- paste("raises", case$raises)+ } else {+ ok <- !failed && fa$.fa_same(case$result, got)+ expected <- fa$.fa_show(case$result)+ }+ if (ok) {+ passed <- passed + 1+ next+ }+ if (length(failures) < 8) {+ shown <- vapply(seq_along(case$args), function(j) {+ n <- names(case$args)[j]+ paste0(if (!is.null(n) && nzchar(n)) paste0(n, " = ") else "", fa$.fa_show(case$args[[j]], 80L))+ }, "")+ label <- switch(if (is.null(case$derived)) "" else case$derived, edge = "(edge) ", derived = "(derived) ", "")+ failures[[length(failures) + 1L]] <- list(+ case = i - 1, call = paste0(label, job$func, "(", paste(shown, collapse = ", "), ")"),+ expected = expected,+ got = if (failed) paste("raised an error:", conditionMessage(got)) else fa$.fa_show(got))+ }+ }++ micro <- NULL+ if (length(cases) && length(failures) == 0 && recorded) {+ best <- function(f) {+ calls <- lapply(head(cases, recorded), `[[`, "args")+ runs <- 0+ spent <- 0+ fastest <- Inf+ while (runs < 3 || (spent < job$budget && runs < 2000)) {+ t <- proc.time()[["elapsed"]]+ for (a in calls) try(do.call(f, a), silent = TRUE)+ took <- proc.time()[["elapsed"]] - t+ fastest <- min(fastest, took)+ spent <- spent + took+ runs <- runs + 1+ }+ per_pass <- if (fastest > 0) fastest else spent / runs # the timer counts milliseconds+ per_pass / length(calls) * 1e9+ }+ r <- best(original)+ rs <- best(port)+ micro <- list(original_ns = r, rust_ns = rs, speedup = if (rs > 0) r / rs else 0)+ }+ report <- list(total = length(cases), derived = length(derived),+ edges = sum(vapply(derived, function(c) identical(c$derived, "edge"), TRUE)),+ passed = passed, failed = length(cases) - passed, failures = failures, micro = micro)+ writeLines(fa$.fa_json(report), job$out, useBytes = TRUE)+}diff --git a/src/r/startup.R b/src/r/startup.Rnew file mode 100644index 0000000..9649d1f--- /dev/null+++ b/src/r/startup.R@@ -0,0 +1,92 @@+# fast-anything's R startup file: R_PROFILE_USER points here while fast-anything profiles or+# records an app, so the app runs with its own command line. Not meant to be used by hand.+# FAST_ANYTHING_MODE=profile: Rprof samples the whole run.+# FAST_ANYTHING_MODE=record: .fast_anything_wrap(f) records calls to f (fast-anything adds a+# line calling it right after the function's definition).+# The user's own startup file (R_PROFILE_USER, ./.Rprofile or ~/.Rprofile) still runs, at the end.++local({+ mode <- Sys.getenv("FAST_ANYTHING_MODE")+ fa <- new.env()+ sys.source(Sys.getenv("FAST_ANYTHING_BRIDGE"), envir = fa)++ if (mode == "profile") {+ out <- Sys.getenv("FAST_ANYTHING_OUT")+ start <- proc.time()[["elapsed"]]+ utils::Rprof(out, interval = 0.005)+ reg.finalizer(fa, function(e) {+ utils::Rprof(NULL)+ writeLines(format(proc.time()[["elapsed"]] - start, digits = 15), paste0(out, ".wall"))+ }, onexit = TRUE)+ # kept reachable, so the finalizer runs when R exits, not at the next garbage collection+ assign(".fast_anything_profile", fa, envir = globalenv())+ }++ if (mode == "record") {+ state <- new.env()+ state$limit <- as.integer(Sys.getenv("FAST_ANYTHING_RECORD_LIMIT", "500"))+ state$calls <- 0+ state$skipped <- 0+ state$unsupported <- character()+ state$kept <- list()+ state$seed <- 64087 # our own generator: the app's random numbers stay as they are++ random <- function(n) { # 1..n+ state$seed <- (state$seed * 69069 + 1) %% 4294967296+ floor(state$seed / 4294967296 * n) + 1+ }++ record <- function(f, args) {+ state$calls <- state$calls + 1+ slot <- if (length(state$kept) < state$limit) length(state$kept) + 1 else random(state$calls)+ case <- NULL+ if (slot <= state$limit) {+ case <- tryCatch(list(args = args, json = fa$.fa_json(unname(args))), fa_unsupported = function(e) {+ state$skipped <- state$skipped + 1+ state$unsupported <- union(state$unsupported, conditionMessage(e))+ NULL+ })+ }+ result <- tryCatch(do.call(f, args), error = function(e) e)+ if (inherits(result, "error")) {+ if (!is.null(case)) {+ case$raises <- class(result)[1]+ state$kept[[slot]] <- case+ }+ stop(result)+ }+ if (!is.null(case)) {+ json <- tryCatch(fa$.fa_json(result), fa_unsupported = function(e) {+ state$skipped <- state$skipped + 1+ state$unsupported <- union(state$unsupported, conditionMessage(e))+ NULL+ })+ if (!is.null(json)) {+ case$result <- result+ case$result_json <- json+ state$kept[slot] <- list(case)+ }+ }+ result+ }++ assign(".fast_anything_wrap", function(f) fa$.fa_like(f, function(args) record(f, args)), envir = globalenv())++ reg.finalizer(state, function(e) {+ out <- Sys.getenv("FAST_ANYTHING_RECORD_OUT")+ lines <- vapply(state$kept, function(c) {+ tail <- if (is.null(c$raises)) paste0("\"result\":", c$result_json) else paste0("\"raises\":", fa$.fa_str(c$raises))+ paste0("{\"args\":", c$json, ",", tail, "}")+ }, "")+ writeLines(enc2utf8(lines), out, useBytes = TRUE)+ saveRDS(lapply(state$kept, function(c) c[c("args", "result", "raises")]), sub("\\.jsonl$", ".rds", out))+ meta <- list(calls = state$calls, kept = length(state$kept), skipped = state$skipped,+ unsupported = as.list(state$unsupported), mutates = FALSE)+ writeLines(fa$.fa_json(meta), Sys.getenv("FAST_ANYTHING_RECORD_META"))+ }, onexit = TRUE)+ }++ user <- Sys.getenv("FAST_ANYTHING_USER_RPROFILE")+ if (!nzchar(user)) user <- if (file.exists(".Rprofile")) ".Rprofile" else path.expand("~/.Rprofile")+ if (file.exists(user)) sys.source(user, envir = globalenv())+})diff --git a/src/state.rs b/src/state.rsindex 7c3a6ae..7ceb3a3 100644--- a/src/state.rs+++ b/src/state.rs@@ -11,7 +11,7 @@ use std::fs;use std::path::{Path, PathBuf};const GITIGNORE: &str = "# fast-anything: commit ports/*/src and Cargo.toml (your Rust ports); skip the rest\n\-target/\nlib/\nbin/\nbackup/\nhook/\nchildren/\nrunner.*\nrecorder.*\nDescribe.java\n*.txt\njob-*.json\nprofile.*\n*.pprof\nverify.json\n*.jsonl\n*.meta.json\n*.log\n";+target/\nlib/\nbin/\nbackup/\nhook/\nchildren/\nrunner.*\nrecorder.*\nDescribe.java\n*.txt\njob-*.json\nprofile.*\n*.pprof\nverify.json\n*.jsonl\n*.meta.json\n*.log\njob-*.R\nstartup.R\nbridge.R\nRprof.out*\n*.rds\n";#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(default)]