Skip to content

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.

fast-anything 0.2.0: Java and Go

EL4CTEO2c8b960a2d43
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 6267b1a..3b16dfe 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "fast-anything",
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "Find the slow 5% of your app, port just that to Rust, and prove it still behaves the same.",
"author": {
"name": "EL4CTEO"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bb7541d..30ba53f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -30,6 +30,14 @@ jobs:
- uses: ruby/setup-ruby@v1
with:
ruby-version: "3.4"
+ - uses: actions/setup-java@v6
+ with:
+ distribution: temurin
+ java-version: "25"
+ - uses: actions/setup-go@v7
+ with:
+ go-version: stable
+ cache: false
- uses: Swatinem/rust-cache@v2
- run: cargo fmt --check
- run: cargo clippy --all-targets -- -D warnings
@@ -75,3 +83,31 @@ jobs:
$fa bench --runs 2
$fa disable
git diff --exit-code fuzzy.rb
+ - name: end to end, Java
+ working-directory: examples/fuzzy-dedupe-java
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- java App.java
+ $fa port
+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs
+ $fa verify
+ $fa enable
+ java --enable-native-access=ALL-UNNAMED App.java
+ $fa bench --runs 2
+ $fa disable
+ git diff --exit-code Fuzzy.java
+ test -z "$(git status --porcelain .)"
+ - name: end to end, Go
+ working-directory: examples/fuzzy-dedupe-go
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- go run .
+ $fa port
+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs
+ $fa verify
+ $fa enable
+ go run .
+ $fa bench --runs 2
+ $fa disable
+ git diff --exit-code fuzzy.go main.go
+ test -z "$(git status --porcelain .)"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a05f6d4..d207699 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,12 @@
# Changelog
+## 0.2.0
+
+- Java (22+): apps run as `java App.java`. Profiled with Flight Recorder, parsed with javac's own parser, ports called through the FFM API.
+- Go (1.22+): apps run as `go run .`. Profiled with pprof, bench times a prebuilt binary so the compiler isn't counted. Ports load through the Windows loader or dlopen.
+- Ports for the C-bridge languages are now verified by fast-anything itself, in a child process, so a crashing port can't take it down.
+- Temporary edits made while profiling or recording are backed up in `.fast/backup` and restored even after an interrupted run.
+
## 0.1.0
- Profile, port, verify, enable, bench and report for Python (PyO3), Node.js/TypeScript (napi-rs) and Ruby (C ABI + JSON via Fiddle, no headers needed).
diff --git a/Cargo.lock b/Cargo.lock
index bcfc58c..3e8e30f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -58,6 +58,12 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
[[package]]
name = "clap"
version = "4.6.9"
@@ -106,10 +112,11 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "fast-anything"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"anyhow",
"clap",
+ "libloading",
"serde",
"serde_json",
]
@@ -132,6 +139,16 @@ version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+[[package]]
+name = "libloading"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
[[package]]
name = "memchr"
version = "2.8.3"
diff --git a/Cargo.toml b/Cargo.toml
index da380eb..ec8a0de 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,13 +1,13 @@
[package]
name = "fast-anything"
-version = "0.1.0"
+version = "0.2.0"
edition = "2024"
rust-version = "1.88"
description = "Find the slow 5% of your app, have your coding agent rewrite just that in Rust, and prove it still behaves the same."
license = "MIT"
readme = "README.md"
repository = "https://github.com/EL4CTEO/fast-anything"
-keywords = ["performance", "python", "nodejs", "profiling", "ai-agents"]
+keywords = ["performance", "python", "nodejs", "java", "ai-agents"]
categories = ["command-line-utilities", "development-tools::profiling"]
exclude = ["examples/*/.fast", ".github", "docs/assets"]
@@ -18,6 +18,7 @@ path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
clap = { version = "4.6.9", features = ["derive"] }
+libloading = "0.9.1"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
diff --git a/README.md b/README.md
index 0d7f78f..e672120 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,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-2563eb" alt="Python, Node, TypeScript, Ruby">
+ <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%20Go-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Go">
<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>
@@ -31,7 +31,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 / -- ruby app.rb
+fast-anything go --agent claude -- python app.py # or: -- node app.ts / ruby app.rb / java App.java / go run .
```
Or step by step:
@@ -62,7 +62,9 @@ Real runs on an i5-10500, Windows 11. Reproduce them from [`examples/`](examples
|---|---|---|
| Python fuzzy dedupe (700 names) | 4.91s | **42ms, 116×** |
| TypeScript fuzzy dedupe (2,000 names) | 3.11s | **155ms, 20×** |
+| Go fuzzy dedupe (3,000 names) | 3.02s | **144ms, 21×** |
| Ruby fuzzy dedupe (400 names) | 3.13s | **228ms, 14×** |
+| Java fuzzy dedupe (4,000 names) | 3.50s | **1.18s, 3×** (11× on the function; the rest is JVM startup) |
fast-anything ports the outermost loop it can, not the tiny function called inside it, so the app crosses into Rust once instead of millions of times. Porting only the inner `levenshtein` gave 35× and 1.9×.
@@ -85,11 +87,13 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| Python 3.10+ | PyO3 | ✅ |
| JavaScript / TypeScript (Node 22+) | napi-rs | ✅ |
| Ruby 3.3+ | C ABI + JSON, through Ruby's built-in Fiddle | ✅ |
-| Go, PHP, Java | the same C bridge | next |
+| Java 22+ (`java App.java`) | the same C bridge, through the FFM API | ✅ |
+| Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo) | ✅ |
+| PHP, C, C++ | the same C bridge | next |
-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`). `scan` says why anything else can't move yet.
+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`). In Java that means static methods, in Go plain functions. `scan` says why anything else can't move yet.
-Ruby needs no headers, compiler or libclang: the port is a plain Rust library with one C entry point taking and returning JSON. Any language that can call C can use that bridge.
+Ruby, Java and Go 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.
## License
diff --git a/examples/fuzzy-dedupe-go/fuzzy.go b/examples/fuzzy-dedupe-go/fuzzy.go
new file mode 100644
index 0000000..7670475
--- /dev/null
+++ b/examples/fuzzy-dedupe-go/fuzzy.go
@@ -0,0 +1,49 @@
+package main
+
+import "strings"
+
+// levenshtein is the edit distance: how many inserts, deletes or substitutions turn a into b.
+func levenshtein(a, b string) int {
+ ra, rb := []rune(a), []rune(b)
+ if len(ra) < len(rb) {
+ ra, rb = rb, ra
+ }
+ previous := make([]int, len(rb)+1)
+ for j := range previous {
+ previous[j] = j
+ }
+ for i := 1; i <= len(ra); i++ {
+ current := make([]int, len(rb)+1)
+ current[0] = i
+ for j := 1; j <= len(rb); j++ {
+ cost := 1
+ if ra[i-1] == rb[j-1] {
+ cost = 0
+ }
+ current[j] = min(previous[j]+1, current[j-1]+1, previous[j-1]+cost)
+ }
+ previous = current
+ }
+ return previous[len(rb)]
+}
+
+func normalize(name string) string {
+ return strings.Join(strings.Fields(strings.ToLower(name)), " ")
+}
+
+// findDuplicates returns index pairs of names within maxDistance edits of each other.
+func findDuplicates(names []string, maxDistance int) [][2]int {
+ clean := make([]string, len(names))
+ for i, n := range names {
+ clean[i] = normalize(n)
+ }
+ var pairs [][2]int
+ for i := range clean {
+ for j := i + 1; j < len(clean); j++ {
+ if levenshtein(clean[i], clean[j]) <= maxDistance {
+ pairs = append(pairs, [2]int{i, j})
+ }
+ }
+ }
+ return pairs
+}
diff --git a/examples/fuzzy-dedupe-go/go.mod b/examples/fuzzy-dedupe-go/go.mod
new file mode 100644
index 0000000..a97d4ad
--- /dev/null
+++ b/examples/fuzzy-dedupe-go/go.mod
@@ -0,0 +1,3 @@
+module example.com/fuzzy
+
+go 1.22
diff --git a/examples/fuzzy-dedupe-go/main.go b/examples/fuzzy-dedupe-go/main.go
new file mode 100644
index 0000000..e6ffb9a
--- /dev/null
+++ b/examples/fuzzy-dedupe-go/main.go
@@ -0,0 +1,43 @@
+// Find near-duplicate customer names, the slow way.
+//
+// go run .
+package main
+
+import (
+ "fmt"
+ "math/rand"
+)
+
+var first = []string{"Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",
+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"}
+var last = []string{"Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka",
+ "Wang", "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"}
+
+func makeNames(count int, seed int64) []string {
+ rng := rand.New(rand.NewSource(seed))
+ names := make([]string, count)
+ for k := range names {
+ name := []rune(first[rng.Intn(len(first))] + " " + last[rng.Intn(len(last))])
+ if rng.Float64() < 0.35 {
+ name[rng.Intn(len(name))] = rune("aeiourstln"[rng.Intn(10)])
+ }
+ names[k] = string(name)
+ }
+ return names
+}
+
+func main() {
+ names := makeNames(3000, 7)
+ pairs := findDuplicates(names, 2)
+ fmt.Printf("%d names, %d likely duplicate pairs\n", len(names), len(pairs))
+ shown := 0
+ for _, p := range pairs {
+ if shown == 5 {
+ break
+ }
+ if names[p[0]] != names[p[1]] {
+ fmt.Printf(" %s ~ %s\n", names[p[0]], names[p[1]])
+ shown++
+ }
+ }
+}
diff --git a/examples/fuzzy-dedupe-go/reference/port.rs b/examples/fuzzy-dedupe-go/reference/port.rs
new file mode 100644
index 0000000..6708f72
--- /dev/null
+++ b/examples/fuzzy-dedupe-go/reference/port.rs
@@ -0,0 +1,74 @@
+//! Reference port of findDuplicates (with levenshtein and normalize inside it):
+//! what a good agent run produces. CI uses it to test the pipeline without an agent.
+#![allow(non_snake_case)]
+
+/// Go's strings.Join(strings.Fields(strings.ToLower(name)), " "), as characters.
+fn normalize(name: &str) -> Vec<char> {
+ let lower = name.to_lowercase();
+ let mut out = Vec::with_capacity(lower.len());
+ for word in lower.split(char::is_whitespace).filter(|w| !w.is_empty()) {
+ if !out.is_empty() {
+ out.push(' ');
+ }
+ out.extend(word.chars());
+ }
+ out
+}
+
+pub fn findDuplicates(names: Vec<String>, maxDistance: i64) -> Result<Vec<[i64; 2]>, String> {
+ if maxDistance < 0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<char>> = names.iter().map(|n| normalize(n)).collect();
+ Ok(pairs(&clean, maxDistance as usize).into_iter().map(|(i, j)| [i as i64, j as i64]).collect())
+}
+
+/// Edit distance, one row on the shorter side, common prefix and suffix skipped.
+fn distance<T: PartialEq>(a: &[T], b: &[T], row: &mut Vec<usize>) -> usize {
+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[prefix..], &b[prefix..]);
+ let suffix = a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[..a.len() - suffix], &b[..b.len() - suffix]);
+ let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
+ if short.is_empty() {
+ return long.len();
+ }
+ 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()]
+}
+
+/// All (i, j) with i < j and distance <= max, in the original loop order, spread over threads.
+fn pairs<T: PartialEq + Sync>(clean: &[Vec<T>], max: usize) -> Vec<(usize, usize)> {
+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(clean.len().max(1));
+ let mut found: Vec<(usize, usize)> = std::thread::scope(|s| {
+ let workers: Vec<_> = (0..threads)
+ .map(|t| {
+ s.spawn(move || {
+ let mut row = Vec::new();
+ let mut out = Vec::new();
+ for i in (t..clean.len()).step_by(threads) {
+ for j in i + 1..clean.len() {
+ if clean[i].len().abs_diff(clean[j].len()) <= max && distance(&clean[i], &clean[j], &mut row) <= max {
+ out.push((i, j));
+ }
+ }
+ }
+ out
+ })
+ })
+ .collect();
+ workers.into_iter().flat_map(|w| w.join().expect("worker panicked")).collect()
+ });
+ found.sort_unstable();
+ found
+}
diff --git a/examples/fuzzy-dedupe-java/App.java b/examples/fuzzy-dedupe-java/App.java
new file mode 100644
index 0000000..baec008
--- /dev/null
+++ b/examples/fuzzy-dedupe-java/App.java
@@ -0,0 +1,38 @@
+// Find near-duplicate customer names, the slow way.
+// java App.java
+import java.util.Random;
+
+public class App {
+ static final String[] FIRST = {"Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",
+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"};
+ static final String[] LAST = {"Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka",
+ "Wang", "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"};
+
+ static String[] makeNames(int count, long seed) {
+ Random rng = new Random(seed);
+ String[] names = new String[count];
+ for (int k = 0; k < count; k++) {
+ String name = FIRST[rng.nextInt(FIRST.length)] + " " + LAST[rng.nextInt(LAST.length)];
+ if (rng.nextDouble() < 0.35) {
+ int i = rng.nextInt(name.length());
+ name = name.substring(0, i) + "aeiourstln".charAt(rng.nextInt(10)) + name.substring(i + 1);
+ }
+ names[k] = name;
+ }
+ return names;
+ }
+
+ public static void main(String[] args) {
+ String[] names = makeNames(4000, 7);
+ int[][] pairs = Fuzzy.findDuplicates(names, 2);
+ System.out.println(names.length + " names, " + pairs.length + " likely duplicate pairs");
+ int shown = 0;
+ for (int[] p : pairs) {
+ if (shown == 5) break;
+ if (!names[p[0]].equals(names[p[1]])) {
+ System.out.println(" " + names[p[0]] + " ~ " + names[p[1]]);
+ shown++;
+ }
+ }
+ }
+}
diff --git a/examples/fuzzy-dedupe-java/Fuzzy.java b/examples/fuzzy-dedupe-java/Fuzzy.java
new file mode 100644
index 0000000..b2a8438
--- /dev/null
+++ b/examples/fuzzy-dedupe-java/Fuzzy.java
@@ -0,0 +1,44 @@
+// Fuzzy string matching helpers.
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+class Fuzzy {
+ // Edit distance: how many inserts, deletes or substitutions turn a into b.
+ static int levenshtein(String a, String b) {
+ if (a.length() < b.length()) {
+ String t = a;
+ a = b;
+ b = t;
+ }
+ int[] previous = new int[b.length() + 1];
+ for (int j = 0; j <= b.length(); j++) previous[j] = j;
+ for (int i = 1; i <= a.length(); i++) {
+ int[] current = new int[b.length() + 1];
+ current[0] = i;
+ for (int j = 1; j <= b.length(); j++) {
+ int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;
+ current[j] = Math.min(Math.min(previous[j] + 1, current[j - 1] + 1), previous[j - 1] + cost);
+ }
+ previous = current;
+ }
+ return previous[b.length()];
+ }
+
+ static String normalize(String name) {
+ return String.join(" ", name.toLowerCase(Locale.ROOT).trim().split("\\s+"));
+ }
+
+ // Index pairs of names within maxDistance edits of each other.
+ static int[][] findDuplicates(String[] names, int maxDistance) {
+ String[] clean = new String[names.length];
+ for (int i = 0; i < names.length; i++) clean[i] = normalize(names[i]);
+ List<int[]> pairs = new ArrayList<>();
+ for (int i = 0; i < clean.length; i++) {
+ for (int j = i + 1; j < clean.length; j++) {
+ if (levenshtein(clean[i], clean[j]) <= maxDistance) pairs.add(new int[]{i, j});
+ }
+ }
+ return pairs.toArray(new int[0][]);
+ }
+}
diff --git a/examples/fuzzy-dedupe-java/reference/port.rs b/examples/fuzzy-dedupe-java/reference/port.rs
new file mode 100644
index 0000000..0656fcd
--- /dev/null
+++ b/examples/fuzzy-dedupe-java/reference/port.rs
@@ -0,0 +1,75 @@
+//! Reference port of Fuzzy.findDuplicates (with levenshtein and normalize inside it):
+//! what a good agent run produces. CI uses it to test the pipeline without an agent.
+#![allow(non_snake_case)]
+
+/// Java's String.join(" ", s.toLowerCase(Locale.ROOT).trim().split("\\s+")), as UTF-16 units.
+fn normalize(name: &str) -> Vec<u16> {
+ let lower = name.to_lowercase();
+ let trimmed = lower.trim_matches(|c: char| c <= ' ');
+ let mut out = Vec::with_capacity(trimmed.len());
+ for word in trimmed.split(|c: char| matches!(c, ' ' | '\t' | '\n' | '\x0B' | '\x0C' | '\r')).filter(|w| !w.is_empty()) {
+ if !out.is_empty() {
+ out.push(u16::from(b' '));
+ }
+ out.extend(word.encode_utf16());
+ }
+ out
+}
+
+pub fn findDuplicates(names: Vec<String>, maxDistance: i32) -> Result<Vec<[i32; 2]>, String> {
+ if maxDistance < 0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<u16>> = names.iter().map(|n| normalize(n)).collect();
+ Ok(pairs(&clean, maxDistance as usize).into_iter().map(|(i, j)| [i as i32, j as i32]).collect())
+}
+
+/// Edit distance, one row on the shorter side, common prefix and suffix skipped.
+fn distance<T: PartialEq>(a: &[T], b: &[T], row: &mut Vec<usize>) -> usize {
+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[prefix..], &b[prefix..]);
+ let suffix = a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[..a.len() - suffix], &b[..b.len() - suffix]);
+ let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
+ if short.is_empty() {
+ return long.len();
+ }
+ 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()]
+}
+
+/// All (i, j) with i < j and distance <= max, in the original loop order, spread over threads.
+fn pairs<T: PartialEq + Sync>(clean: &[Vec<T>], max: usize) -> Vec<(usize, usize)> {
+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(clean.len().max(1));
+ let mut found: Vec<(usize, usize)> = std::thread::scope(|s| {
+ let workers: Vec<_> = (0..threads)
+ .map(|t| {
+ s.spawn(move || {
+ let mut row = Vec::new();
+ let mut out = Vec::new();
+ for i in (t..clean.len()).step_by(threads) {
+ for j in i + 1..clean.len() {
+ if clean[i].len().abs_diff(clean[j].len()) <= max && distance(&clean[i], &clean[j], &mut row) <= max {
+ out.push((i, j));
+ }
+ }
+ }
+ out
+ })
+ })
+ .collect();
+ workers.into_iter().flat_map(|w| w.join().expect("worker panicked")).collect()
+ });
+ found.sort_unstable();
+ found
+}
diff --git a/npm/fast-anything/package.json b/npm/fast-anything/package.json
index fa5ea19..0d3cd3e 100644
--- a/npm/fast-anything/package.json
+++ b/npm/fast-anything/package.json
@@ -1,13 +1,15 @@
{
"name": "@el4cteo/fast-anything",
- "version": "0.1.0",
- "description": "Don't rewrite it in Rust. Rewrite the 5% that's slow: profile Python, Node or Ruby apps, port the hot functions with your coding agent, prove they behave the same.",
+ "version": "0.2.0",
+ "description": "Don't rewrite it in Rust. Rewrite the 5% that's slow: profile Python, Node, Ruby, Java or Go apps, port the hot functions with your coding agent, prove they behave the same.",
"keywords": [
"rust",
"python",
"nodejs",
"typescript",
"ruby",
+ "java",
+ "golang",
"performance",
"optimization",
"profiler",
@@ -42,11 +44,11 @@
"node": ">=18"
},
"optionalDependencies": {
- "@el4cteo/fast-anything-win32-x64": "0.1.0",
- "@el4cteo/fast-anything-linux-x64": "0.1.0",
- "@el4cteo/fast-anything-linux-arm64": "0.1.0",
- "@el4cteo/fast-anything-darwin-arm64": "0.1.0",
- "@el4cteo/fast-anything-darwin-x64": "0.1.0"
+ "@el4cteo/fast-anything-win32-x64": "0.2.0",
+ "@el4cteo/fast-anything-linux-x64": "0.2.0",
+ "@el4cteo/fast-anything-linux-arm64": "0.2.0",
+ "@el4cteo/fast-anything-darwin-arm64": "0.2.0",
+ "@el4cteo/fast-anything-darwin-x64": "0.2.0"
},
"publishConfig": {
"access": "public"
diff --git a/skills/fast-anything/SKILL.md b/skills/fast-anything/SKILL.md
index 6bae65f..65c2ff7 100644
--- a/skills/fast-anything/SKILL.md
+++ b/skills/fast-anything/SKILL.md
@@ -1,6 +1,6 @@
---
name: fast-anything
-description: Speed up a slow Python, Node.js/TypeScript or Ruby app by porting its hottest pure functions to Rust (PyO3) and proving each port gives the same results on real recorded calls. Use when the user wants their Python code faster, asks about hot paths or profiling, or says "rewrite the slow part in Rust".
+description: Speed up a slow Python, Node.js/TypeScript, Ruby, Java or Go app by porting its hottest pure functions to Rust and proving each port gives the same results on real recorded calls. Use when the user wants their Python code faster, asks about hot paths or profiling, or says "rewrite the slow part in Rust".
---
# fast-anything
@@ -15,7 +15,7 @@ The `fast-anything` CLI measures, records, builds, checks and swaps. You write t
Skip anything under 2% of the run: porting it can't make a visible difference.
2. **Port**: `fast-anything port <id>`. It re-runs the app, records up to 500 real calls, and creates
`.fast/ports/<id>/` with a stub `src/lib.rs` and a `TASK.md`. Read TASK.md fully.
-3. **Write the Rust** in `src/lib.rs` (Ruby: `src/port.rs`; `src/lib.rs` there is generated glue):
+3. **Write the Rust** in `src/lib.rs` (Ruby, Java, Go: `src/port.rs`; `src/lib.rs` there is generated glue):
- Same semantics: Unicode code points (`.chars()`; JavaScript compares UTF-16 units), integer ranges, float operation order, error cases.
- Fast: borrow, no needless allocation, ASCII fast paths, `with_capacity`.
- Keep the function and module names. Run `cargo check` in the crate.
diff --git a/src/backend.rs b/src/backend.rs
index f8f2e8b..ae04da6 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::{node, python, ruby};
+use crate::{golang, java, node, python, ruby};
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use std::fs;
@@ -18,6 +18,8 @@ pub enum Lang {
Python,
Node,
Ruby,
+ Java,
+ Go,
}
#[derive(Deserialize)]
@@ -43,18 +45,29 @@ impl Lang {
Ok(Lang::Node)
} else if ruby::is_ruby(program) {
Ok(Lang::Ruby)
+ } else if java::is_java(program) {
+ Ok(Lang::Java)
+ } else if golang::is_go(program) {
+ Ok(Lang::Go)
} else {
bail!(
- "fast-anything speaks Python, Node.js (JavaScript/TypeScript) and Ruby. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js\n fast-anything scan -- ruby app.rb"
+ "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java and Go. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run ."
)
}
}
+ /// Ports called through the C entry point, with the port in src/port.rs.
+ pub fn c_bridge(self) -> bool {
+ matches!(self, Lang::Ruby | Lang::Java | Lang::Go)
+ }
+
pub fn label(self) -> &'static str {
match self {
Lang::Python => "Python",
Lang::Node => "JavaScript",
Lang::Ruby => "Ruby",
+ Lang::Java => "Java",
+ Lang::Go => "Go",
}
}
@@ -63,6 +76,8 @@ impl Lang {
Lang::Python => python::resolve(program, root),
Lang::Node => node::resolve(program, root),
Lang::Ruby => ruby::resolve(program, root),
+ Lang::Java => java::resolve(program, root),
+ Lang::Go => golang::resolve(program, root),
}
}
@@ -71,6 +86,8 @@ impl Lang {
Lang::Python => python::profile(ctx, exe, args),
Lang::Node => node::profile(ctx, exe, args),
Lang::Ruby => ruby::profile(ctx, exe, args),
+ Lang::Java => java::profile(ctx, exe, args),
+ Lang::Go => golang::profile(ctx, exe, args),
}
}
@@ -87,6 +104,8 @@ impl Lang {
Lang::Python => python::record(ctx, exe, args, hs, out, limit),
Lang::Node => node::record(ctx, exe, args, hs, out, limit),
Lang::Ruby => ruby::record(ctx, exe, args, hs, out, limit),
+ Lang::Java => java::record(ctx, exe, args, hs, out, limit),
+ Lang::Go => golang::record(ctx, exe, args, hs, out, limit),
}
}
@@ -95,6 +114,8 @@ impl Lang {
Lang::Python => python::scaffold(ctx, hs, helpers, port),
Lang::Node => node::scaffold(ctx, hs, helpers, port),
Lang::Ruby => ruby::scaffold(ctx, hs, helpers, port),
+ Lang::Java => java::scaffold(ctx, hs, helpers, port),
+ Lang::Go => golang::scaffold(ctx, hs, helpers, port),
}
}
@@ -103,6 +124,8 @@ impl Lang {
Lang::Python => python::verify(ctx, port),
Lang::Node => node::verify(ctx, port),
Lang::Ruby => ruby::verify(ctx, port),
+ Lang::Java => java::verify(ctx, port),
+ Lang::Go => golang::verify(ctx, port),
}
}
@@ -111,6 +134,8 @@ impl Lang {
Lang::Python => python::enable(ctx, port),
Lang::Node => node::enable(ctx, port),
Lang::Ruby => ruby::enable(ctx, port),
+ Lang::Java => java::enable(ctx, port),
+ Lang::Go => golang::enable(ctx, port),
}
}
@@ -119,6 +144,17 @@ impl Lang {
Lang::Python => python::disable(ctx, port),
Lang::Node => node::disable(ctx, port),
Lang::Ruby => ruby::disable(ctx, port),
+ Lang::Java => java::disable(ctx, port),
+ Lang::Go => golang::disable(ctx, port),
+ }
+ }
+
+ /// What bench runs: (program, args). Go apps are built once, so the compiler isn't timed.
+ pub fn bench_command(self, ctx: &Ctx) -> Result<(String, Vec<String>)> {
+ let exe = ctx.runtime()?;
+ match self {
+ Lang::Go => golang::bench_command(ctx, exe),
+ _ => Ok((exe.to_string(), ctx.state.command[1..].to_vec())),
}
}
@@ -135,8 +171,8 @@ impl Lang {
Lang::Python if cfg!(windows) => format!("{ext}.pyd"),
Lang::Python => format!("{ext}.abi3.so"),
Lang::Node => format!("{ext}.node"),
- // loaded with Fiddle.dlopen: the platform's own library name
- Lang::Ruby => built.clone(),
+ // loaded through a C FFI (Fiddle, FFM, ...): the platform's own library name
+ Lang::Ruby | Lang::Java | Lang::Go => built.clone(),
};
(built, dest)
}
diff --git a/src/bench.rs b/src/bench.rs
index 0b63502..0bc927e 100644
--- a/src/bench.rs
+++ b/src/bench.rs
@@ -68,8 +68,8 @@ fn time_once(ctx: &Ctx, python: &str, args: &[String], original: bool) -> Result
}
pub fn run(ctx: &Ctx, runs: usize) -> Result<BenchResult> {
- let python = ctx.runtime()?;
- let args = &ctx.state.command[1..];
+ let (python, args) = ctx.state.lang.bench_command(ctx)?;
+ let (python, args) = (python.as_str(), args.as_slice());
let ports: Vec<String> = ctx.state.ports.values().filter(|p| p.enabled).map(|p| p.id.clone()).collect();
if ports.is_empty() {
ui::warn("no ports are enabled yet, so before and after are the same code");
diff --git a/src/doctor.rs b/src/doctor.rs
index 2a9834f..7de1914 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -35,6 +35,18 @@ pub fn run() -> Result<()> {
need: "for Ruby apps (3.3+)",
hint: "https://ruby-lang.org",
},
+ Check {
+ name: "java",
+ found: version("java", &["--version"]),
+ need: "for Java apps (22+)",
+ hint: "https://adoptium.net",
+ },
+ Check {
+ name: "go",
+ found: version("go", &["version"]),
+ need: "for Go apps (1.22+)",
+ hint: "https://go.dev/dl",
+ },
Check {
name: "claude",
found: version("claude", &["--version"]),
@@ -63,7 +75,7 @@ pub fn run() -> Result<()> {
}
}
ensure!(checks[0].found.is_some(), "Rust is needed to build ports");
- ensure!(checks[1..4].iter().any(|c| c.found.is_some()), "install Python, Node.js or Ruby");
+ ensure!(checks[1..6].iter().any(|c| c.found.is_some()), "install Python, Node.js, Ruby, Java or Go");
ui::ok("ready");
Ok(())
}
diff --git a/src/golang.rs b/src/golang.rs
new file mode 100644
index 0000000..eb6a181
--- /dev/null
+++ b/src/golang.rs
@@ -0,0 +1,534 @@
+//! Go backend: apps run as go run . (or a package path, or a list of files). fast-anything builds
+//! the binary itself, so timing never includes the compiler. Profiled with runtime/pprof, read with
+//! go/parser, and bridged with the Windows loader or dlopen through cgo elsewhere.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::{Hotspot, Param};
+use crate::native::{self, Flavor, Patches};
+use crate::python::DISABLE_ENV;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{self, combined, output, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde::Deserialize;
+use std::collections::HashMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+const DESCRIBE: &str = include_str!("golang/describe.go");
+const REC: &str = include_str!("golang/rec.go");
+const HOOKS: &str = include_str!("golang/hooks.go");
+const BRIDGE: &str = include_str!("golang/bridge.go");
+const BRIDGE_WINDOWS: &str = include_str!("golang/bridge_windows.go");
+const BRIDGE_UNIX: &str = include_str!("golang/bridge_unix.go");
+const BRIDGE_NOCGO: &str = include_str!("golang/bridge_nocgo.go");
+/// go build flags that take the next argument as their value.
+const VALUE_FLAGS: &[&str] = &[
+ "-C",
+ "-p",
+ "-tags",
+ "-ldflags",
+ "-gcflags",
+ "-asmflags",
+ "-mod",
+ "-modfile",
+ "-pgo",
+ "-exec",
+ "-overlay",
+ "-toolexec",
+];
+
+pub fn is_go(program: &str) -> bool {
+ util::program_stem(program) == "go"
+}
+
+pub fn resolve(program: &str, root: &Path) -> Result<String> {
+ let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };
+ let out = output(Command::new(&prog).args(["env", "GOROOT", "GOVERSION"]).current_dir(root), "go")?;
+ 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 goroot = lines.next().unwrap_or_default().trim().to_string();
+ let version: Vec<u32> = lines
+ .next()
+ .unwrap_or_default()
+ .trim()
+ .trim_start_matches("go")
+ .split('.')
+ .filter_map(|s| s.parse().ok())
+ .collect();
+ ensure!(version.as_slice() >= &[1, 22][..], "Go 1.22 or newer is needed (found {version:?})");
+ let exe = Path::new(&goroot).join("bin").join(if cfg!(windows) { "go.exe" } else { "go" });
+ Ok(exe.to_string_lossy().into_owned())
+}
+
+/// go run [build flags] <package | files...> [app args]
+struct GoRun {
+ flags: Vec<String>,
+ targets: Vec<String>,
+ args: Vec<String>,
+}
+
+impl GoRun {
+ fn parse(args: &[String]) -> Result<GoRun> {
+ ensure!(
+ args.first().map(String::as_str) == Some("run"),
+ "start the command with go run (e.g. fast-anything scan -- go run .)"
+ );
+ let mut i = 1;
+ let mut flags = Vec::new();
+ while i < args.len() && args[i].starts_with('-') {
+ flags.push(args[i].clone());
+ if VALUE_FLAGS.contains(&args[i].as_str()) && i + 1 < args.len() {
+ flags.push(args[i + 1].clone());
+ i += 1;
+ }
+ i += 1;
+ }
+ let mut targets = Vec::new();
+ while i < args.len() && args[i].ends_with(".go") {
+ targets.push(args[i].clone());
+ i += 1;
+ }
+ if targets.is_empty() {
+ let pkg = args.get(i).context("go run needs a package: go run .")?;
+ ensure!(
+ pkg.starts_with('.') || Path::new(pkg).is_absolute(),
+ "use a local package path like go run . or go run ./cmd/app"
+ );
+ targets.push(pkg.clone());
+ i += 1;
+ }
+ Ok(GoRun { flags, targets, args: args[i..].to_vec() })
+ }
+
+ fn files_mode(&self) -> bool {
+ self.targets[0].ends_with(".go")
+ }
+
+ /// Folder of the main package.
+ fn main_dir(&self, root: &Path) -> PathBuf {
+ let t = Path::new(&self.targets[0]);
+ let dir = if self.files_mode() { t.parent().unwrap_or(Path::new(".")) } else { t };
+ util::absolute(&root.join(dir))
+ }
+}
+
+fn binary(ctx: &Ctx) -> PathBuf {
+ ctx.fast.join("bin").join(if cfg!(windows) { "app.exe" } else { "app" })
+}
+
+/// go build the app into .fast/bin, with extra generated files in the main package.
+fn build(ctx: &Ctx, go: &str, run: &GoRun, extra: &[PathBuf]) -> Result<PathBuf> {
+ let bin = binary(ctx);
+ fs::create_dir_all(bin.parent().context("bin")?)?;
+ let mut targets = run.targets.clone();
+ if run.files_mode() {
+ targets.extend(extra.iter().map(|p| p.to_string_lossy().into_owned()));
+ }
+ let out = output(
+ Command::new(go).arg("build").args(&run.flags).arg("-o").arg(&bin).args(&targets).current_dir(&ctx.root),
+ "go",
+ )?;
+ ensure!(out.status.success(), "go build failed:\n{}", tail(&combined(&out), 30));
+ Ok(bin)
+}
+
+/// The command bench times: the binary, built once.
+pub fn bench_command(ctx: &Ctx, go: &str) -> Result<(String, Vec<String>)> {
+ let run = GoRun::parse(&ctx.state.command[1..])?;
+ let bin = build(ctx, go, &run, &[])?;
+ Ok((bin.to_string_lossy().into_owned(), run.args))
+}
+
+#[derive(Deserialize, Clone)]
+struct Func {
+ symbol: String,
+ package: String,
+ pkg_name: String,
+ path: PathBuf,
+ name: String,
+ line: u32,
+ end_line: u32,
+ params: Vec<Param>,
+ returns: Option<String>,
+ blockers: Vec<String>,
+ warnings: Vec<String>,
+ calls: Vec<String>,
+ source: String,
+}
+
+fn describe(ctx: &Ctx, go: &str) -> Result<Vec<Func>> {
+ let dir = ctx.fast.join("describe");
+ fs::create_dir_all(&dir)?;
+ fs::write(dir.join("describe.go"), DESCRIBE)?;
+ let out = ctx.fast.join("go-funcs.json");
+ let run = output(
+ Command::new(go)
+ .args(["run", "describe.go"])
+ .arg(&ctx.root)
+ .arg(&out)
+ .current_dir(&dir)
+ .env("GO111MODULE", "off")
+ .stdin(Stdio::null()),
+ "go",
+ )?;
+ ensure!(run.status.success(), "reading the Go sources failed:\n{}", tail(&combined(&run), 20));
+ serde_json::from_str(&fs::read_to_string(&out)?).context("reading the function list")
+}
+
+fn module_of(ctx: &Ctx, f: &Func) -> String {
+ if f.package == "main" {
+ return "main".into();
+ }
+ let dir = f.path.parent().unwrap_or(&ctx.root);
+ let rel = util::forward_slashes(dir.strip_prefix(&ctx.root).unwrap_or(dir));
+ if rel.is_empty() { f.pkg_name.clone() } else { rel.replace('/', ".") }
+}
+
+fn hotspot(ctx: &Ctx, f: &Func, flat: f64, cum: f64) -> Hotspot {
+ Hotspot {
+ file: util::forward_slashes(f.path.strip_prefix(&ctx.root).unwrap_or(&f.path)),
+ line: f.line,
+ end_line: f.end_line,
+ name: f.name.clone(),
+ qualname: f.name.clone(),
+ module: Some(module_of(ctx, f)),
+ kind: "function".into(),
+ tottime: flat,
+ cumtime: cum,
+ portability: if f.blockers.is_empty() { 0.9 } else { 0.0 },
+ blockers: f.blockers.clone(),
+ warnings: f.warnings.clone(),
+ params: f.params.clone(),
+ returns: f.returns.clone(),
+ source: f.source.clone(),
+ calls: f.calls.clone(),
+ owner: Some(f.symbol.clone()),
+ ..Hotspot::default()
+ }
+}
+
+fn find_body(name: &str, hint: u32) -> impl Fn(&str) -> Option<usize> {
+ let header = format!("func {name}(");
+ let generic = format!("func {name}[");
+ move |text: &str| native::body_line(text, hint, |l| l.starts_with(&header) || l.starts_with(&generic))
+}
+
+/// Generated files and a deferred hook in main, for one build. Undone by the returned Patches.
+fn instrument(
+ ctx: &Ctx,
+ funcs: &[Func],
+ run: &GoRun,
+ extra: Vec<(PathBuf, String)>,
+) -> Result<(Patches, Vec<PathBuf>)> {
+ let main_dir = run.main_dir(&ctx.root);
+ let main = funcs
+ .iter()
+ .find(|f| {
+ f.package == "main" && f.name == "main" && f.path.parent().map(util::absolute) == Some(main_dir.clone())
+ })
+ .context("no func main() in the main package")?;
+ let mut patches = Patches::new(ctx)?;
+ let text = fs::read_to_string(&main.path)?;
+ let hooked =
+ native::insert_in_body(&text, "//", "hooks", "defer fastAnythingDone()", find_body("main", main.line))?;
+ let hooks = main_dir.join("fast_anything_hooks.go");
+ patches.write(&hooks, HOOKS)?;
+ patches.write(&main.path, &hooked)?;
+ let mut created = vec![hooks];
+ for (path, text) in extra {
+ if path.extension().is_some_and(|e| e == "go")
+ && !fs::read_to_string(&path).is_ok_and(|t| t.contains(">>> fast-anything"))
+ {
+ created.push(path.clone());
+ }
+ patches.write(&path, &text)?;
+ }
+ created.retain(|p| p.parent() == Some(main_dir.as_path()));
+ Ok((patches, created))
+}
+
+fn parse_duration(s: &str) -> Option<f64> {
+ let s = s.trim();
+ if s == "0" {
+ return Some(0.0);
+ }
+ let split = s.find(|c: char| c.is_ascii_alphabetic() || c == 'µ')?;
+ let (num, unit) = s.split_at(split);
+ let n: f64 = num.parse().ok()?;
+ Some(match unit {
+ "ns" => n * 1e-9,
+ "us" | "µs" => n * 1e-6,
+ "ms" => n * 1e-3,
+ "s" => n,
+ "mins" | "min" => n * 60.0,
+ "hrs" | "h" => n * 3600.0,
+ _ => return None,
+ })
+}
+
+/// (flat, cum) seconds per symbol from go tool pprof -top.
+fn parse_top(text: &str) -> HashMap<String, (f64, f64)> {
+ let mut out = HashMap::new();
+ let mut rows = false;
+ for line in text.lines() {
+ if line.trim_start().starts_with("flat") {
+ rows = true;
+ continue;
+ }
+ if !rows {
+ continue;
+ }
+ let cols: Vec<&str> = line.split_whitespace().collect();
+ if cols.len() < 6 {
+ continue;
+ }
+ let (Some(flat), Some(cum)) = (parse_duration(cols[0]), parse_duration(cols[3])) else { continue };
+ let name = cols[5..].join(" ");
+ let name = name.trim_end_matches(" (inline)").to_string();
+ let e = out.entry(name).or_insert((0.0, 0.0));
+ e.0 += flat;
+ e.1 = f64::max(e.1, cum);
+ }
+ out
+}
+
+pub fn profile(ctx: &Ctx, go: &str, args: &[String]) -> Result<Profile> {
+ let run = GoRun::parse(args)?;
+ let funcs = describe(ctx, go)?;
+ let (mut patches, extra) = instrument(ctx, &funcs, &run, vec![])?;
+ let bin = build(ctx, go, &run, &extra);
+ patches.restore()?;
+ let bin = bin?;
+ let pprof = ctx.fast.join("cpu.pprof");
+ let _ = fs::remove_file(&pprof);
+ let started = Instant::now();
+ let out = output(
+ Command::new(&bin)
+ .args(&run.args)
+ .current_dir(&ctx.root)
+ .env("FAST_ANYTHING_PPROF", &pprof)
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null()),
+ "the app",
+ )?;
+ let wall = started.elapsed().as_secs_f64();
+ ensure!(out.status.success(), "the app failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ ensure!(pprof.exists(), "no profile was written: does main return normally (no os.Exit)?");
+ let top = output(
+ Command::new(go).args(["tool", "pprof", "-top", "-cum", "-nodecount=1000"]).arg(&bin).arg(&pprof),
+ "go tool pprof",
+ )?;
+ ensure!(top.status.success(), "reading the profile failed:\n{}", tail(&combined(&top), 10));
+ let times = parse_top(&String::from_utf8_lossy(&top.stdout));
+ let mut functions: Vec<Hotspot> = Vec::new();
+ for f in &funcs {
+ let sampled = times.get(&f.symbol).copied();
+ let helper = funcs
+ .iter()
+ .any(|g| times.contains_key(&g.symbol) && g.path.parent() == f.path.parent() && g.calls.contains(&f.name));
+ if sampled.is_some() || helper {
+ let (flat, cum) = sampled.unwrap_or_default();
+ functions.push(hotspot(ctx, f, flat, cum));
+ }
+ }
+ Ok(Profile { wall, base: ".".into(), functions })
+}
+
+fn pkg_name(ctx: &Ctx, hs: &Hotspot) -> Result<String> {
+ let text = fs::read_to_string(ctx.root.join(&hs.file))?;
+ text.lines()
+ .find_map(|l| l.trim().strip_prefix("package ").map(|p| p.trim().to_string()))
+ .context("no package clause")
+}
+
+fn arg_list(hs: &Hotspot) -> String {
+ hs.params.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", ")
+}
+
+fn ret(hs: &Hotspot) -> String {
+ hs.returns.clone().unwrap_or_default()
+}
+
+pub fn record(ctx: &Ctx, go: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
+ let run = GoRun::parse(args)?;
+ let funcs = describe(ctx, go)?;
+ let file = ctx.root.join(&hs.file);
+ let text = fs::read_to_string(&file)?;
+ let casts: Vec<String> = hs
+ .params
+ .iter()
+ .enumerate()
+ .map(|(i, p)| format!("a[{i}].({})", p.annotation.as_deref().unwrap_or("any")))
+ .collect();
+ let prologue = format!(
+ "if !fastAnythingRecInside {{\n\treturn fastAnythingRec([]any{{{args}}}, func(a []any) any {{ return {name}({casts}) }}).({ret})\n}}",
+ args = arg_list(hs),
+ name = hs.name,
+ casts = casts.join(", "),
+ ret = ret(hs),
+ );
+ let patched =
+ native::insert_in_body(&text, "//", &format!("recording {}", hs.id), &prologue, find_body(&hs.name, hs.line))?;
+ let rec = REC.replace("/*PKG*/", &pkg_name(ctx, hs)?).replace("/*ID*/", &hs.id);
+ let rec_path = native::sibling(&file, "fast_anything_rec.go")?;
+ let (mut patches, extra) = instrument(ctx, &funcs, &run, vec![(rec_path, rec), (file.clone(), patched)])?;
+ let bin = build(ctx, go, &run, &extra);
+ patches.restore()?;
+ let bin = bin?;
+ let meta = out.with_extension("meta.json");
+ let _ = fs::remove_file(&meta);
+ let app = output(
+ Command::new(&bin)
+ .args(&run.args)
+ .current_dir(&ctx.root)
+ .env("FAST_ANYTHING_RECORD_OUT", out)
+ .env("FAST_ANYTHING_RECORD_META", &meta)
+ .env("FAST_ANYTHING_RECORD_LIMIT", limit.to_string())
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null()),
+ "the app",
+ )?;
+ ensure!(app.status.success(), "the app failed while recording ({}):\n{}", app.status, tail(&combined(&app), 30));
+ serde_json::from_str(
+ &fs::read_to_string(&meta).context("nothing was recorded: does main return normally (no os.Exit)?")?,
+ )
+ .context("reading the recording summary")
+}
+
+// ------------------------------------------------------------------ the crate
+
+/// Rust type for a Go type.
+pub fn rust_type(t: &str) -> Option<String> {
+ let t = t.trim();
+ Some(match t {
+ "int" | "int64" => "i64".into(),
+ "int32" | "rune" => "i32".into(),
+ "int16" => "i16".into(),
+ "int8" => "i8".into(),
+ "uint" | "uint64" => "u64".into(),
+ "uint32" => "u32".into(),
+ "uint16" => "u16".into(),
+ "uint8" | "byte" => "u8".into(),
+ "float64" => "f64".into(),
+ "float32" => "f32".into(),
+ "string" => "String".into(),
+ "bool" => "bool".into(),
+ _ if t.starts_with("[]") => format!("Vec<{}>", rust_type(&t[2..])?),
+ _ if t.starts_with("map[string]") => format!("std::collections::HashMap<String, {}>", rust_type(&t[11..])?),
+ _ if t.starts_with('[') => {
+ let (n, inner) = t[1..].split_once(']')?;
+ format!("[{}; {}]", rust_type(inner)?, n.parse::<usize>().ok()?)
+ }
+ _ => return None,
+ })
+}
+
+pub const FLAVOR: Flavor = Flavor {
+ lang: backend::Lang::Go,
+ fence: "go",
+ rust_type,
+ default_json: |_| None,
+ rules: &[
+ "Go `int` is `i64` and wraps on overflow: use `wrapping_*` where the original can overflow.",
+ "Go strings are UTF-8 bytes: `len(s)` and `s[i]` are bytes, `for _, r := range s` and `[]rune(s)` are characters. Do the same in Rust.",
+ "A nil slice or map arrives (and may be returned) as an empty Vec or HashMap: fast-anything treats them as equal.",
+ "Map iteration order is random in Go: return results in the order the original does when it's deterministic.",
+ ],
+};
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ native::scaffold(ctx, hs, helpers, port, &FLAVOR)
+}
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ native::verify(ctx, port, true)
+}
+
+// ------------------------------------------------------------------ the bridge
+
+fn suffix(port: &Port) -> String {
+ util::slug(&port.id)
+}
+
+fn bridge_files(file: &Path, port: &Port) -> Result<[PathBuf; 4]> {
+ let s = suffix(port);
+ Ok([
+ native::sibling(file, &format!("fast_anything_{s}.go"))?,
+ native::sibling(file, &format!("fast_anything_{s}_windows.go"))?,
+ native::sibling(file, &format!("fast_anything_{s}_unix.go"))?,
+ native::sibling(file, &format!("fast_anything_{s}_nocgo.go"))?,
+ ])
+}
+
+fn hotspot_of<'a>(ctx: &'a Ctx, port: &Port) -> Result<&'a Hotspot> {
+ ctx.state
+ .hotspots
+ .iter()
+ .find(|h| h.id == port.id)
+ .with_context(|| format!("{} isn't in the last scan: scan again", port.id))
+}
+
+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let hs = hotspot_of(ctx, port)?;
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ if GoRun::parse(&ctx.state.command[1..]).is_ok_and(|r| r.files_mode()) {
+ bail!("the app runs as go run <files>: run it as go run . so Go picks up the bridge files, then scan again");
+ }
+ let s = suffix(port);
+ let (_, lib) = port.lang.artifact(&port.ext);
+ let lib = serde_json::to_string(&util::forward_slashes(&ctx.lib_dir().join(lib)))?;
+ let params: Vec<String> =
+ hs.params.iter().map(|p| format!("{} {}", p.name, p.annotation.as_deref().unwrap_or("any"))).collect();
+ let fill = |t: &str| {
+ t.replace("/*PKG*/", &pkg_name(ctx, hs).unwrap_or_else(|_| "main".into()))
+ .replace("/*ID*/", &port.id)
+ .replace("/*S*/", &s)
+ .replace("/*PARAMS*/", &params.join(", "))
+ .replace("/*ARGS*/", &arg_list(hs))
+ .replace("/*RET*/", &ret(hs))
+ .replace("/*LIB*/", &lib)
+ };
+ let prologue = format!("if faR, faOK := faFast_{s}({}); faOK {{\n\treturn faR\n}}", arg_list(hs));
+ let patched = native::insert_in_body(&text, "//", &port.id, &prologue, find_body(&port.func, hs.line))?;
+ for (path, template) in bridge_files(&file, port)?.iter().zip([BRIDGE, BRIDGE_WINDOWS, BRIDGE_UNIX, BRIDGE_NOCGO]) {
+ fs::write(path, fill(template))?;
+ }
+ 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, native::strip_in_body(&text, "//", &port.id)).with_context(|| format!("writing {}", port.file))?;
+ for path in bridge_files(&file, port)? {
+ if path.exists() {
+ fs::remove_file(path)?;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn go_commands_and_profiles() {
+ let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
+ let r = GoRun::parse(&s(&["run", "-tags", "x", ".", "--n", "3"])).unwrap();
+ assert_eq!((r.flags.len(), r.targets[0].as_str(), r.args.len()), (2, ".", 2));
+ let r = GoRun::parse(&s(&["run", "main.go", "fuzzy.go", "a"])).unwrap();
+ assert!(r.files_mode() && r.targets.len() == 2 && r.args == ["a"]);
+ assert!(GoRun::parse(&s(&["build", "."])).is_err());
+ let top = " flat flat% sum% cum cum%\n 210ms 14.38% 14.38% 1.42s 97.26% main.main\n 1210ms 82.88% 97.26% 1210ms 82.88% main.work (inline)\n";
+ let t = parse_top(top);
+ assert!((t["main.main"].1 - 1.42).abs() < 1e-9 && (t["main.work"].0 - 1.21).abs() < 1e-9);
+ assert_eq!(rust_type("[][2]int").as_deref(), Some("Vec<[i64; 2]>"));
+ assert_eq!(rust_type("map[string][]float64").as_deref(), Some("std::collections::HashMap<String, Vec<f64>>"));
+ assert!(is_go("go") && is_go("C:\\Go\\bin\\go.exe") && !is_go("gofmt"));
+ }
+}
diff --git a/src/golang/bridge.go b/src/golang/bridge.go
new file mode 100644
index 0000000..474f731
--- /dev/null
+++ b/src/golang/bridge.go
@@ -0,0 +1,122 @@
+// Code generated by fast-anything. DO NOT EDIT.
+// Calls the verified Rust port of /*ID*/. FAST_ANYTHING_DISABLE=1 runs the Go version instead.
+// Remove with fast-anything disable /*ID*/
+package /*PKG*/
+
+import (
+ "encoding/json"
+ "errors"
+ "math"
+ "os"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "unicode/utf8"
+)
+
+var (
+ faOnce_/*S*/ sync.Once
+ faOn_/*S*/ bool
+)
+
+func faFast_/*S*/(/*PARAMS*/) (/*RET*/, bool) {
+ var zero /*RET*/
+ faOnce_/*S*/.Do(func() { faOn_/*S*/ = os.Getenv("FAST_ANYTHING_DISABLE") == "" && faLoad_/*S*/(/*LIB*/) })
+ if !faOn_/*S*/ {
+ return zero, false
+ }
+ in, err := faJSON_/*S*/([]any{/*ARGS*/})
+ if err != nil {
+ return zero, false // NaN, Inf or non-UTF-8 input: let Go handle it
+ }
+ var reply struct {
+ Ok json.RawMessage `json:"ok"`
+ Error *string `json:"error"`
+ }
+ if err := json.Unmarshal(faInvoke_/*S*/([]byte(in)), &reply); err != nil {
+ panic("fast-anything: " + err.Error())
+ }
+ if reply.Error != nil {
+ panic("fast-anything: " + *reply.Error)
+ }
+ var out /*RET*/
+ if err := json.Unmarshal(reply.Ok, &out); err != nil {
+ panic("fast-anything: " + err.Error())
+ }
+ return out, true
+}
+
+func faJSON_/*S*/(v any) (string, error) {
+ var b strings.Builder
+ err := faEnc_/*S*/(&b, reflect.ValueOf(v))
+ return b.String(), err
+}
+
+func faEnc_/*S*/(b *strings.Builder, v reflect.Value) error {
+ if !v.IsValid() {
+ b.WriteString("null")
+ return nil
+ }
+ switch v.Kind() {
+ case reflect.Interface, reflect.Pointer:
+ if v.IsNil() {
+ b.WriteString("null")
+ return nil
+ }
+ return faEnc_/*S*/(b, v.Elem())
+ case reflect.Bool:
+ b.WriteString(strconv.FormatBool(v.Bool()))
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ b.WriteString(strconv.FormatInt(v.Int(), 10))
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ b.WriteString(strconv.FormatUint(v.Uint(), 10))
+ case reflect.Float32, reflect.Float64:
+ f := v.Float()
+ if math.IsNaN(f) || math.IsInf(f, 0) {
+ return errors.New("NaN or Inf")
+ }
+ bits := 64
+ if v.Kind() == reflect.Float32 {
+ bits = 32
+ }
+ b.WriteString(strconv.FormatFloat(f, 'g', -1, bits))
+ case reflect.String:
+ if !utf8.ValidString(v.String()) {
+ return errors.New("string that isn't UTF-8")
+ }
+ q, _ := json.Marshal(v.String())
+ b.Write(q)
+ case reflect.Slice, reflect.Array:
+ b.WriteByte('[')
+ for i := 0; i < v.Len(); i++ {
+ if i > 0 {
+ b.WriteByte(',')
+ }
+ if err := faEnc_/*S*/(b, v.Index(i)); err != nil {
+ return err
+ }
+ }
+ b.WriteByte(']')
+ case reflect.Map:
+ keys := v.MapKeys()
+ sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
+ b.WriteByte('{')
+ for i, k := range keys {
+ if i > 0 {
+ b.WriteByte(',')
+ }
+ q, _ := json.Marshal(k.String())
+ b.Write(q)
+ b.WriteByte(':')
+ if err := faEnc_/*S*/(b, v.MapIndex(k)); err != nil {
+ return err
+ }
+ }
+ b.WriteByte('}')
+ default:
+ return errors.New(v.Type().String())
+ }
+ return nil
+}
diff --git a/src/golang/bridge_nocgo.go b/src/golang/bridge_nocgo.go
new file mode 100644
index 0000000..1f47c93
--- /dev/null
+++ b/src/golang/bridge_nocgo.go
@@ -0,0 +1,8 @@
+// Code generated by fast-anything. DO NOT EDIT. Without cgo there's no dlopen: the Go version runs.
+//go:build !windows && !cgo
+
+package /*PKG*/
+
+func faLoad_/*S*/(path string) bool { return false }
+
+func faInvoke_/*S*/(in []byte) []byte { return nil }
diff --git a/src/golang/bridge_unix.go b/src/golang/bridge_unix.go
new file mode 100644
index 0000000..3d9259c
--- /dev/null
+++ b/src/golang/bridge_unix.go
@@ -0,0 +1,49 @@
+// Code generated by fast-anything. DO NOT EDIT. Loads the Rust port with dlopen (needs cgo).
+//go:build !windows && cgo
+
+package /*PKG*/
+
+/*
+#cgo linux LDFLAGS: -ldl
+#include <dlfcn.h>
+#include <stdlib.h>
+typedef unsigned char *(*fa_call_t)(const unsigned char *, size_t, size_t *);
+typedef void (*fa_free_t)(unsigned char *, size_t);
+static void *fa_open(const char *path) { return dlopen(path, RTLD_NOW | RTLD_LOCAL); }
+static void *fa_sym(void *lib, const char *name) { return dlsym(lib, name); }
+static unsigned char *fa_do_call(void *f, const unsigned char *in, size_t len, size_t *out) { return ((fa_call_t)f)(in, len, out); }
+static void fa_do_free(void *f, unsigned char *p, size_t n) { ((fa_free_t)f)(p, n); }
+*/
+import "C"
+
+import "unsafe"
+
+var faSyms_/*S*/ [2]unsafe.Pointer
+
+func faLoad_/*S*/(path string) bool {
+ cpath := C.CString(path)
+ defer C.free(unsafe.Pointer(cpath))
+ lib := C.fa_open(cpath)
+ if lib == nil {
+ return false
+ }
+ for i, name := range []string{"fa_call", "fa_free"} {
+ cname := C.CString(name)
+ faSyms_/*S*/[i] = C.fa_sym(lib, cname)
+ C.free(unsafe.Pointer(cname))
+ if faSyms_/*S*/[i] == nil {
+ return false
+ }
+ }
+ return true
+}
+
+func faInvoke_/*S*/(in []byte) []byte {
+ cin := C.CBytes(in)
+ defer C.free(cin)
+ var n C.size_t
+ p := C.fa_do_call(faSyms_/*S*/[0], (*C.uchar)(cin), C.size_t(len(in)), &n)
+ out := C.GoBytes(unsafe.Pointer(p), C.int(n))
+ C.fa_do_free(faSyms_/*S*/[1], p, n)
+ return out
+}
diff --git a/src/golang/bridge_windows.go b/src/golang/bridge_windows.go
new file mode 100644
index 0000000..3f046fe
--- /dev/null
+++ b/src/golang/bridge_windows.go
@@ -0,0 +1,27 @@
+// Code generated by fast-anything. DO NOT EDIT. Loads the Rust port with the Windows loader.
+package /*PKG*/
+
+import (
+ "syscall"
+ "unsafe"
+)
+
+var faProcs_/*S*/ [2]*syscall.LazyProc
+
+func faLoad_/*S*/(path string) bool {
+ dll := syscall.NewLazyDLL(path)
+ if dll.Load() != nil {
+ return false
+ }
+ faProcs_/*S*/ = [2]*syscall.LazyProc{dll.NewProc("fa_call"), dll.NewProc("fa_free")}
+ return faProcs_/*S*/[0].Find() == nil && faProcs_/*S*/[1].Find() == nil
+}
+
+func faInvoke_/*S*/(in []byte) []byte {
+ var n uintptr
+ p, _, _ := faProcs_/*S*/[0].Call(uintptr(unsafe.Pointer(unsafe.SliceData(in))), uintptr(len(in)), uintptr(unsafe.Pointer(&n)))
+ out := make([]byte, n)
+ copy(out, unsafe.Slice((*byte)(unsafe.Pointer(p)), n))
+ faProcs_/*S*/[1].Call(p, n)
+ return out
+}
diff --git a/src/golang/describe.go b/src/golang/describe.go
new file mode 100644
index 0000000..bad9e54
--- /dev/null
+++ b/src/golang/describe.go
@@ -0,0 +1,289 @@
+// Go side of fast-anything's scan: reads the module with go/parser and describes every function.
+// The CLI runs it as go run describe.go <module root> <out.json>. Not meant to be run by hand.
+package main
+
+import (
+ "bufio"
+ "encoding/json"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "go/types"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+)
+
+type Param struct {
+ Name string `json:"name"`
+ Annotation string `json:"annotation"`
+}
+
+type Fn struct {
+ Symbol string `json:"symbol"`
+ Package string `json:"package"`
+ PkgName string `json:"pkg_name"`
+ Path string `json:"path"`
+ Name string `json:"name"`
+ Line int `json:"line"`
+ EndLine int `json:"end_line"`
+ Params []Param `json:"params"`
+ Returns *string `json:"returns"`
+ Blockers []string `json:"blockers"`
+ Warnings []string `json:"warnings"`
+ Calls []string `json:"calls"`
+ Source string `json:"source"`
+}
+
+var ioPkgs = map[string]bool{"os": true, "io": true, "bufio": true, "net": true, "http": true, "ioutil": true, "exec": true, "syscall": true, "log": true, "slog": true, "sql": true}
+var basic = map[string]bool{"int": true, "int8": true, "int16": true, "int32": true, "int64": true, "uint": true, "uint8": true, "uint16": true,
+ "uint32": true, "uint64": true, "float32": true, "float64": true, "string": true, "bool": true, "byte": true, "rune": true}
+var arrayRe = regexp.MustCompile(`^\[\d+\]`)
+
+func supported(t string) bool {
+ switch {
+ case basic[t]:
+ return true
+ case strings.HasPrefix(t, "[]"):
+ return supported(t[2:])
+ case arrayRe.MatchString(t):
+ return supported(arrayRe.ReplaceAllString(t, ""))
+ case strings.HasPrefix(t, "map[string]"):
+ return supported(t[len("map[string]"):])
+ }
+ return false
+}
+
+func modulePath(root string) string {
+ f, err := os.Open(filepath.Join(root, "go.mod"))
+ if err != nil {
+ return ""
+ }
+ defer f.Close()
+ s := bufio.NewScanner(f)
+ for s.Scan() {
+ if l := strings.TrimSpace(s.Text()); strings.HasPrefix(l, "module ") {
+ return strings.Trim(strings.TrimSpace(l[7:]), "\"")
+ }
+ }
+ return ""
+}
+
+func first(xs []string, n int) string {
+ if len(xs) > n {
+ xs = xs[:n]
+ }
+ return strings.Join(xs, ", ")
+}
+
+func main() {
+ root, out := os.Args[1], os.Args[2]
+ mod := modulePath(root)
+ fset := token.NewFileSet()
+ fns := []Fn{}
+ filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return nil
+ }
+ if d.IsDir() {
+ n := d.Name()
+ if p != root && (strings.HasPrefix(n, ".") || n == "vendor" || n == "testdata" || n == "node_modules") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") || strings.HasPrefix(d.Name(), "fast_anything") {
+ return nil
+ }
+ src, err := os.ReadFile(p)
+ if err != nil {
+ return nil
+ }
+ f, err := parser.ParseFile(fset, p, src, parser.SkipObjectResolution)
+ if err != nil {
+ return nil
+ }
+ pkg := "main"
+ if f.Name.Name != "main" {
+ rel, _ := filepath.Rel(root, filepath.Dir(p))
+ pkg = mod
+ if rel != "." {
+ pkg = mod + "/" + filepath.ToSlash(rel)
+ }
+ }
+ funcs, vars := map[string]bool{}, map[string]bool{}
+ for _, decl := range f.Decls {
+ switch d := decl.(type) {
+ case *ast.FuncDecl:
+ if d.Recv == nil {
+ funcs[d.Name.Name] = true
+ }
+ case *ast.GenDecl:
+ if d.Tok == token.VAR {
+ for _, s := range d.Specs {
+ for _, n := range s.(*ast.ValueSpec).Names {
+ vars[n.Name] = true
+ }
+ }
+ }
+ }
+ }
+ for _, decl := range f.Decls {
+ fd, ok := decl.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ fns = append(fns, describe(fset, src, p, pkg, f.Name.Name, fd, funcs, vars))
+ }
+ return nil
+ })
+ data, _ := json.Marshal(fns)
+ os.WriteFile(out, data, 0o644)
+}
+
+func describe(fset *token.FileSet, src []byte, path, pkg, pkgName string, fd *ast.FuncDecl, funcs, vars map[string]bool) Fn {
+ name := fd.Name.Name
+ fn := Fn{Package: pkg, PkgName: pkgName, Path: path, Name: name, Blockers: []string{}, Warnings: []string{}, Calls: []string{}, Params: []Param{}}
+ fn.Symbol = pkg + "." + name
+ if fd.Recv != nil && len(fd.Recv.List) > 0 {
+ recv := types.ExprString(fd.Recv.List[0].Type)
+ if strings.HasPrefix(recv, "*") {
+ fn.Symbol = pkg + ".(" + recv + ")." + name
+ } else {
+ fn.Symbol = pkg + "." + recv + "." + name
+ }
+ fn.Blockers = append(fn.Blockers, "method (plain functions only for now)")
+ }
+ if name == "main" || name == "init" {
+ fn.Blockers = append(fn.Blockers, "the entry point")
+ }
+ if fd.Type.TypeParams != nil && len(fd.Type.TypeParams.List) > 0 {
+ fn.Blockers = append(fn.Blockers, "generic function")
+ }
+ locals := map[string]bool{}
+ for _, field := range fd.Type.Params.List {
+ t := types.ExprString(field.Type)
+ if strings.HasPrefix(t, "...") {
+ fn.Blockers = append(fn.Blockers, "takes variadic arguments")
+ } else if !supported(t) {
+ fn.Blockers = append(fn.Blockers, "takes a "+t)
+ }
+ if len(field.Names) == 0 {
+ fn.Blockers = append(fn.Blockers, "has unnamed parameters")
+ }
+ for _, n := range field.Names {
+ fn.Params = append(fn.Params, Param{Name: n.Name, Annotation: t})
+ locals[n.Name] = true
+ }
+ }
+ results := fd.Type.Results
+ switch {
+ case results == nil || len(results.List) == 0:
+ fn.Blockers = append(fn.Blockers, "returns nothing")
+ case len(results.List) > 1 || len(results.List[0].Names) > 1:
+ fn.Blockers = append(fn.Blockers, "returns more than one value")
+ default:
+ t := types.ExprString(results.List[0].Type)
+ fn.Returns = &t
+ if !supported(t) {
+ fn.Blockers = append(fn.Blockers, "returns a "+t)
+ }
+ if len(results.List[0].Names) > 0 {
+ fn.Blockers = append(fn.Blockers, "has named results")
+ }
+ }
+ io, nondet, helpers := []string{}, []string{}, []string{}
+ seen := map[string]bool{}
+ add := func(list *[]string, s string) {
+ if !seen[s] {
+ seen[s] = true
+ *list = append(*list, s)
+ }
+ }
+ writesGlobal, goroutines, channels := false, false, false
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.GoStmt:
+ goroutines = true
+ case *ast.SendStmt, *ast.SelectStmt:
+ channels = true
+ case *ast.UnaryExpr:
+ if x.Op == token.ARROW {
+ channels = true
+ }
+ case *ast.AssignStmt:
+ for _, l := range x.Lhs {
+ if id, ok := l.(*ast.Ident); ok {
+ if x.Tok == token.DEFINE {
+ locals[id.Name] = true
+ } else if vars[id.Name] && !locals[id.Name] {
+ writesGlobal = true
+ }
+ }
+ }
+ case *ast.ValueSpec:
+ for _, id := range x.Names {
+ locals[id.Name] = true
+ }
+ case *ast.IncDecStmt:
+ if id, ok := x.X.(*ast.Ident); ok && vars[id.Name] && !locals[id.Name] {
+ writesGlobal = true
+ }
+ case *ast.CallExpr:
+ switch f := x.Fun.(type) {
+ case *ast.SelectorExpr:
+ if pk, ok := f.X.(*ast.Ident); ok {
+ call := pk.Name + "." + f.Sel.Name
+ s := f.Sel.Name
+ if ioPkgs[pk.Name] || (pk.Name == "fmt" && (strings.HasPrefix(s, "Print") || strings.HasPrefix(s, "Fprint") || strings.Contains(s, "Scan"))) {
+ add(&io, call)
+ }
+ if pk.Name == "rand" || (pk.Name == "time" && (s == "Now" || s == "Since" || s == "Until" || s == "Sleep")) {
+ add(&nondet, call)
+ }
+ }
+ case *ast.Ident:
+ if f.Name == "println" || f.Name == "print" || f.Name == "panic" && false {
+ add(&io, f.Name)
+ }
+ if funcs[f.Name] && f.Name != name {
+ add(&helpers, f.Name)
+ }
+ }
+ }
+ return true
+ })
+ if len(io) > 0 {
+ fn.Blockers = append(fn.Blockers, "does I/O: "+first(io, 3))
+ }
+ if len(nondet) > 0 {
+ fn.Blockers = append(fn.Blockers, "not deterministic: "+first(nondet, 3))
+ }
+ if goroutines {
+ fn.Blockers = append(fn.Blockers, "starts goroutines")
+ }
+ if channels {
+ fn.Blockers = append(fn.Blockers, "uses channels")
+ }
+ if writesGlobal {
+ fn.Blockers = append(fn.Blockers, "writes package-level variables")
+ }
+ if len(helpers) > 0 {
+ fn.Calls = helpers
+ fn.Warnings = append(fn.Warnings, "calls "+first(helpers, 3)+", they get ported together with it")
+ }
+ lbrace := fset.Position(fd.Body.Lbrace)
+ rest := string(src[lbrace.Offset+1:])
+ if i := strings.IndexByte(rest, '\n'); i >= 0 {
+ rest = rest[:i]
+ }
+ if r := strings.TrimSpace(rest); r != "" && !strings.HasPrefix(r, "//") {
+ fn.Blockers = append(fn.Blockers, "its { doesn't end a line (gofmt it)")
+ }
+ start, end := fset.Position(fd.Pos()), fset.Position(fd.End())
+ fn.Line, fn.EndLine = start.Line, end.Line
+ fn.Source = strings.ReplaceAll(string(src[start.Offset:end.Offset]), "\r", "")
+ return fn
+}
diff --git a/src/golang/hooks.go b/src/golang/hooks.go
new file mode 100644
index 0000000..7e04146
--- /dev/null
+++ b/src/golang/hooks.go
@@ -0,0 +1,30 @@
+// Code generated by fast-anything. DO NOT EDIT. Profiles or records one run; removed afterwards.
+package main
+
+import (
+ "expvar"
+ "os"
+ "runtime/pprof"
+)
+
+var fastAnythingProfFile *os.File
+
+func init() {
+ if path := os.Getenv("FAST_ANYTHING_PPROF"); path != "" {
+ if f, err := os.Create(path); err == nil && pprof.StartCPUProfile(f) == nil {
+ fastAnythingProfFile = f
+ }
+ }
+}
+
+// Deferred at the top of main: stops the profile and saves recordings when main returns.
+func fastAnythingDone() {
+ if fastAnythingProfFile != nil {
+ pprof.StopCPUProfile()
+ fastAnythingProfFile.Close()
+ fastAnythingProfFile = nil
+ }
+ if save, ok := expvar.Get("fast_anything_save").(expvar.Func); ok {
+ save()
+ }
+}
diff --git a/src/golang/rec.go b/src/golang/rec.go
new file mode 100644
index 0000000..776484c
--- /dev/null
+++ b/src/golang/rec.go
@@ -0,0 +1,286 @@
+// Code generated by fast-anything. DO NOT EDIT. Records calls to /*ID*/ for one run; removed afterwards.
+package /*PKG*/
+
+import (
+ "encoding/json"
+ "errors"
+ "expvar"
+ "math"
+ "math/rand"
+ "os"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+)
+
+var (
+ fastAnythingRecInside bool
+ fastAnythingRecMu sync.Mutex
+ fastAnythingRecKept []string
+ fastAnythingRecArgs [][]any
+ fastAnythingRecCalls int64
+ fastAnythingRecSkip int64
+ fastAnythingRecNanos int64
+ fastAnythingRecLimit = 500
+ fastAnythingRecWhy = map[string]bool{}
+ fastAnythingRecFn func([]any) any
+ fastAnythingRecRng = rand.New(rand.NewSource(0xFA57))
+)
+
+func init() {
+ if n, err := strconv.Atoi(os.Getenv("FAST_ANYTHING_RECORD_LIMIT")); err == nil && n > 0 {
+ fastAnythingRecLimit = n
+ }
+ expvar.Publish("fast_anything_save", expvar.Func(func() any { fastAnythingRecSave(); return nil }))
+}
+
+func fastAnythingRec(args []any, fn func([]any) any) any {
+ fastAnythingRecMu.Lock()
+ defer fastAnythingRecMu.Unlock()
+ fastAnythingRecInside = true
+ defer func() { fastAnythingRecInside = false }()
+ fastAnythingRecFn = fn
+ fastAnythingRecCalls++
+ slot := len(fastAnythingRecKept)
+ if slot >= fastAnythingRecLimit {
+ slot = int(fastAnythingRecRng.Int63n(fastAnythingRecCalls))
+ }
+ enc, ok := "", false
+ var copied []any
+ if slot < fastAnythingRecLimit {
+ if e, err := fastAnythingRecJSON(args); err == nil {
+ enc, ok, copied = e, true, fastAnythingRecCopy(reflect.ValueOf(args)).Interface().([]any)
+ } else {
+ fastAnythingRecSkip++
+ fastAnythingRecWhy[err.Error()] = true
+ }
+ }
+ start := time.Now()
+ r := fn(args)
+ fastAnythingRecNanos += time.Since(start).Nanoseconds()
+ if ok {
+ if re, err := fastAnythingRecJSON(r); err == nil {
+ line := `{"args":` + enc + `,"result":` + re + "}"
+ if slot < len(fastAnythingRecKept) {
+ fastAnythingRecKept[slot], fastAnythingRecArgs[slot] = line, copied
+ } else {
+ fastAnythingRecKept = append(fastAnythingRecKept, line)
+ fastAnythingRecArgs = append(fastAnythingRecArgs, copied)
+ }
+ } else {
+ fastAnythingRecSkip++
+ fastAnythingRecWhy[err.Error()] = true
+ }
+ }
+ return r
+}
+
+func fastAnythingRecCopy(v reflect.Value) reflect.Value {
+ switch v.Kind() {
+ case reflect.Interface:
+ if v.IsNil() {
+ return v
+ }
+ c := reflect.New(v.Type()).Elem()
+ c.Set(fastAnythingRecCopy(v.Elem()))
+ return c
+ case reflect.Slice:
+ if v.IsNil() {
+ return v
+ }
+ c := reflect.MakeSlice(v.Type(), v.Len(), v.Len())
+ for i := 0; i < v.Len(); i++ {
+ c.Index(i).Set(fastAnythingRecCopy(v.Index(i)))
+ }
+ return c
+ case reflect.Map:
+ if v.IsNil() {
+ return v
+ }
+ c := reflect.MakeMapWithSize(v.Type(), v.Len())
+ for _, k := range v.MapKeys() {
+ c.SetMapIndex(k, fastAnythingRecCopy(v.MapIndex(k)))
+ }
+ return c
+ }
+ return v
+}
+
+func fastAnythingRecJSON(v any) (string, error) {
+ var b strings.Builder
+ err := fastAnythingRecEnc(&b, reflect.ValueOf(v))
+ return b.String(), err
+}
+
+func fastAnythingRecEnc(b *strings.Builder, v reflect.Value) error {
+ if !v.IsValid() {
+ b.WriteString("null")
+ return nil
+ }
+ switch v.Kind() {
+ case reflect.Interface, reflect.Pointer:
+ if v.IsNil() {
+ b.WriteString("null")
+ return nil
+ }
+ return fastAnythingRecEnc(b, v.Elem())
+ case reflect.Bool:
+ b.WriteString(strconv.FormatBool(v.Bool()))
+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+ b.WriteString(strconv.FormatInt(v.Int(), 10))
+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
+ b.WriteString(strconv.FormatUint(v.Uint(), 10))
+ case reflect.Float32, reflect.Float64:
+ f := v.Float()
+ if math.IsNaN(f) || math.IsInf(f, 0) {
+ return errors.New("NaN or Inf")
+ }
+ bits := 64
+ if v.Kind() == reflect.Float32 {
+ bits = 32
+ }
+ s := strconv.FormatFloat(f, 'g', -1, bits)
+ if !strings.ContainsAny(s, ".e") {
+ s += ".0"
+ }
+ b.WriteString(s)
+ case reflect.String:
+ if !utf8.ValidString(v.String()) {
+ return errors.New("string that isn't UTF-8")
+ }
+ q, _ := json.Marshal(v.String())
+ b.Write(q)
+ case reflect.Slice, reflect.Array:
+ b.WriteByte('[')
+ for i := 0; i < v.Len(); i++ {
+ if i > 0 {
+ b.WriteByte(',')
+ }
+ if err := fastAnythingRecEnc(b, v.Index(i)); err != nil {
+ return err
+ }
+ }
+ b.WriteByte(']')
+ case reflect.Map:
+ if v.Type().Key().Kind() != reflect.String {
+ return errors.New("map without string keys")
+ }
+ keys := v.MapKeys()
+ sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
+ b.WriteByte('{')
+ for i, k := range keys {
+ if i > 0 {
+ b.WriteByte(',')
+ }
+ q, _ := json.Marshal(k.String())
+ b.Write(q)
+ b.WriteByte(':')
+ if err := fastAnythingRecEnc(b, v.MapIndex(k)); err != nil {
+ return err
+ }
+ }
+ b.WriteByte('}')
+ default:
+ return errors.New(v.Type().String())
+ }
+ return nil
+}
+
+var fastAnythingRecSlices = []int{0, 1, 2, 3, 5, 8, 13, 21, 34, 55}
+
+func fastAnythingRecVariants(v any) []any {
+ out := []any{}
+ if s, ok := v.(string); ok {
+ r := []rune(s)
+ for _, n := range fastAnythingRecSlices {
+ if n >= len(r) || len(r) < 2 {
+ break
+ }
+ for rep := 0; rep < map[bool]int{true: 1, false: 3}[n < 2]; rep++ {
+ off := fastAnythingRecRng.Intn(len(r) - n + 1)
+ out = append(out, string(r[off:off+n]))
+ }
+ }
+ return out
+ }
+ rv := reflect.ValueOf(v)
+ if rv.Kind() != reflect.Slice || rv.Len() < 2 {
+ return out
+ }
+ for _, n := range fastAnythingRecSlices {
+ if n >= rv.Len() {
+ break
+ }
+ for rep := 0; rep < map[bool]int{true: 1, false: 3}[n < 2]; rep++ {
+ off := fastAnythingRecRng.Intn(rv.Len() - n + 1)
+ c := reflect.MakeSlice(rv.Type(), n, n)
+ reflect.Copy(c, rv.Slice(off, off+n))
+ out = append(out, fastAnythingRecCopy(c).Interface())
+ }
+ }
+ return out
+}
+
+func fastAnythingRecSave() {
+ fastAnythingRecMu.Lock()
+ defer fastAnythingRecMu.Unlock()
+ fastAnythingRecInside = true
+ derived := []string{}
+ seen := map[string]bool{}
+ start := time.Now()
+ call := func(a []any) (r any, ok bool) {
+ defer func() {
+ if recover() != nil {
+ ok = false
+ }
+ }()
+ return fastAnythingRecFn(a), true
+ }
+outer:
+ for _, args := range fastAnythingRecArgs {
+ if args == nil || fastAnythingRecFn == nil {
+ continue
+ }
+ for i := range args {
+ for _, smaller := range fastAnythingRecVariants(args[i]) {
+ if len(derived) >= 200 || time.Since(start) > 3*time.Second {
+ break outer
+ }
+ next := fastAnythingRecCopy(reflect.ValueOf(args)).Interface().([]any)
+ next[i] = smaller
+ enc, err := fastAnythingRecJSON(next)
+ if err != nil || seen[enc] {
+ continue
+ }
+ seen[enc] = true
+ r, ok := call(next)
+ if !ok {
+ continue
+ }
+ if re, err := fastAnythingRecJSON(r); err == nil {
+ derived = append(derived, `{"args":`+enc+`,"result":`+re+`,"derived":true}`)
+ }
+ }
+ }
+ }
+ var b strings.Builder
+ for _, l := range append(fastAnythingRecKept, derived...) {
+ b.WriteString(l)
+ b.WriteByte('\n')
+ }
+ os.WriteFile(os.Getenv("FAST_ANYTHING_RECORD_OUT"), []byte(b.String()), 0o644)
+ why := []string{}
+ for k := range fastAnythingRecWhy {
+ why = append(why, k)
+ }
+ perCall := 0.0
+ if fastAnythingRecCalls > 0 {
+ perCall = float64(fastAnythingRecNanos) / float64(fastAnythingRecCalls)
+ }
+ meta, _ := json.Marshal(map[string]any{"calls": fastAnythingRecCalls, "kept": len(fastAnythingRecKept), "skipped": fastAnythingRecSkip, "unsupported": why, "original_ns": perCall})
+ os.WriteFile(os.Getenv("FAST_ANYTHING_RECORD_META"), meta, 0o644)
+}
diff --git a/src/java.rs b/src/java.rs
new file mode 100644
index 0000000..ba4580d
--- /dev/null
+++ b/src/java.rs
@@ -0,0 +1,425 @@
+//! Java backend: apps run as java App.java (source-file mode, multi-file since Java 22).
+//! Profiled with Java Flight Recorder, read with javac's own parser, and bridged to the port with
+//! the Foreign Function & Memory API: nothing to install beyond a JDK 22+.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::{Hotspot, Param};
+use crate::native::{self, Flavor, Patches};
+use crate::python::DISABLE_ENV;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{self, combined, output, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde::Deserialize;
+use serde_json::Value;
+use std::collections::{HashMap, HashSet};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+const DESCRIBE: &str = include_str!("java/Describe.java");
+const JSON: &str = include_str!("java/Json.java");
+const REC: &str = include_str!("java/Rec.java");
+const BRIDGE: &str = include_str!("java/Bridge.java");
+/// java options that take the next argument as their value.
+const VALUE_OPTS: &[&str] =
+ &["-cp", "-classpath", "--class-path", "-p", "--module-path", "--add-modules", "--source", "--limit-modules"];
+
+pub fn is_java(program: &str) -> bool {
+ util::program_stem(program) == "java"
+}
+
+pub fn resolve(program: &str, root: &Path) -> Result<String> {
+ let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };
+ let out = output(Command::new(&prog).args(["-XshowSettings:properties", "-version"]).current_dir(root), "java")?;
+ let text = combined(&out);
+ let prop = |key: &str| {
+ text.lines().find_map(|l| {
+ l.trim().strip_prefix(key).and_then(|r| r.trim().strip_prefix('=')).map(|v| v.trim().to_string())
+ })
+ };
+ let home = prop("java.home").context("couldn't read java.home from java -XshowSettings")?;
+ let version: u32 = prop("java.specification.version").and_then(|v| v.parse().ok()).unwrap_or(0);
+ ensure!(
+ version >= 22,
+ "Java 22 or newer is needed (found {version}): it runs multi-file source programs and has the FFM API"
+ );
+ let exe = Path::new(&home).join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
+ Ok(exe.to_string_lossy().into_owned())
+}
+
+fn tool(java: &str, name: &str) -> PathBuf {
+ Path::new(java).with_file_name(if cfg!(windows) { format!("{name}.exe") } else { name.to_string() })
+}
+
+/// The source file in java [options] App.java [args].
+fn entry(args: &[String]) -> Result<&str> {
+ let mut i = 0;
+ while i < args.len() && args[i].starts_with('-') {
+ i += if VALUE_OPTS.contains(&args[i].as_str()) { 2 } else { 1 };
+ }
+ match args.get(i) {
+ Some(f) if f.ends_with(".java") => Ok(f),
+ _ => bail!(
+ "run the app as a source file: fast-anything scan -- java App.java (jar and classpath apps aren't supported yet)"
+ ),
+ }
+}
+
+fn source_files(root: &Path, entry: &str) -> Vec<PathBuf> {
+ let start = root.join(entry).parent().map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf());
+ let mut out = Vec::new();
+ let mut stack = vec![start];
+ while let Some(dir) = stack.pop() {
+ let Ok(entries) = fs::read_dir(&dir) else { continue };
+ for e in entries.flatten() {
+ let p = e.path();
+ let name = e.file_name().to_string_lossy().into_owned();
+ if p.is_dir() {
+ if !name.starts_with('.') && !["target", "build", "out", "node_modules"].contains(&name.as_str()) {
+ stack.push(p);
+ }
+ } else if name.ends_with(".java") && !name.starts_with("FastAnything") {
+ out.push(p);
+ }
+ }
+ }
+ out
+}
+
+#[derive(Deserialize, Clone)]
+struct Method {
+ class: String,
+ owner: String,
+ name: String,
+ path: PathBuf,
+ line: u32,
+ end_line: u32,
+ params: Vec<Param>,
+ returns: String,
+ blockers: Vec<String>,
+ warnings: Vec<String>,
+ calls: Vec<String>,
+ source: String,
+}
+
+fn describe(ctx: &Ctx, java: &str, files: &[PathBuf]) -> Result<Vec<Method>> {
+ let script = ctx.fast.join("Describe.java");
+ fs::write(&script, DESCRIBE)?;
+ let list = ctx.fast.join("java-files.txt");
+ fs::write(&list, files.iter().map(|f| f.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"))?;
+ let out = ctx.fast.join("java-methods.json");
+ let run = output(
+ Command::new(java).arg(&script).arg(&list).arg(&out).current_dir(&ctx.root).stdin(Stdio::null()),
+ "java",
+ )?;
+ ensure!(run.status.success(), "reading the Java sources failed:\n{}", tail(&combined(&run), 20));
+ serde_json::from_str(&fs::read_to_string(&out)?).context("reading the method list")
+}
+
+fn rel(ctx: &Ctx, p: &Path) -> String {
+ util::forward_slashes(p.strip_prefix(&ctx.root).unwrap_or(p))
+}
+
+fn hotspot(ctx: &Ctx, m: &Method, total: f64, wall: f64, own: u64, incl: u64) -> Hotspot {
+ Hotspot {
+ file: rel(ctx, &m.path),
+ line: m.line,
+ end_line: m.end_line,
+ name: m.name.clone(),
+ qualname: m.name.clone(),
+ module: Some(m.class.replace('$', ".")),
+ kind: "function".into(),
+ tottime: own as f64 / total * wall,
+ cumtime: incl as f64 / total * wall,
+ portability: if m.blockers.is_empty() { 0.9 } else { 0.0 },
+ blockers: m.blockers.clone(),
+ warnings: m.warnings.clone(),
+ params: m.params.clone(),
+ returns: Some(m.returns.clone()),
+ source: m.source.clone(),
+ calls: m.calls.clone(),
+ owner: Some(m.owner.clone()),
+ ..Hotspot::default()
+ }
+}
+
+pub fn profile(ctx: &Ctx, java: &str, args: &[String]) -> Result<Profile> {
+ let entry = entry(args)?.to_string();
+ let jfr_file = ctx.fast.join("profile.jfr");
+ let _ = fs::remove_file(&jfr_file);
+ let started = Instant::now();
+ let run = output(
+ Command::new(java)
+ .arg("-XX:StartFlightRecording:filename=.fast/profile.jfr,settings=profile")
+ .arg("-Xlog:jfr+startup=error")
+ .args(args)
+ .current_dir(&ctx.root)
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null()),
+ "java",
+ )?;
+ let wall = started.elapsed().as_secs_f64();
+ ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));
+ let printed = output(
+ Command::new(tool(java, "jfr")).args(["print", "--events", "jdk.ExecutionSample", "--json"]).arg(&jfr_file),
+ "jfr",
+ )?;
+ ensure!(printed.status.success(), "reading the flight recording failed:\n{}", tail(&combined(&printed), 10));
+ let recording: Value = serde_json::from_slice(&printed.stdout).context("parsing the flight recording")?;
+
+ let methods = describe(ctx, java, &source_files(&ctx.root, &entry))?;
+ let mut by_name: HashMap<(String, String), Vec<usize>> = HashMap::new();
+ for (i, m) in methods.iter().enumerate() {
+ by_name.entry((m.class.clone(), m.name.clone())).or_default().push(i);
+ }
+ let (mut total, mut own, mut incl) = (0u64, HashMap::<usize, u64>::new(), HashMap::<usize, u64>::new());
+ for ev in recording["recording"]["events"].as_array().map(Vec::as_slice).unwrap_or_default() {
+ let Some(frames) = ev["values"]["stackTrace"]["frames"].as_array() else { continue };
+ if frames.is_empty() {
+ continue;
+ }
+ total += 1;
+ let mut seen = HashSet::new();
+ for (depth, f) in frames.iter().enumerate() {
+ let class = f["method"]["type"]["name"].as_str().unwrap_or_default().replace('/', ".");
+ let name = f["method"]["name"].as_str().unwrap_or_default().to_string();
+ let Some(cands) = by_name.get(&(class, name)) else { continue };
+ let line = f["lineNumber"].as_i64().unwrap_or(0) as u32;
+ let i =
+ *cands.iter().find(|&&i| methods[i].line <= line && line <= methods[i].end_line).unwrap_or(&cands[0]);
+ if depth == 0 {
+ *own.entry(i).or_default() += 1;
+ }
+ if seen.insert(i) {
+ *incl.entry(i).or_default() += 1;
+ }
+ }
+ }
+ ensure!(total > 0, "the flight recording has no samples: does the app run long enough (a second or more)?");
+ let mut keep: Vec<usize> = incl.keys().copied().collect();
+ let helpers: Vec<usize> = keep
+ .iter()
+ .flat_map(|&i| {
+ let m = &methods[i];
+ methods
+ .iter()
+ .enumerate()
+ .filter(move |(_, h)| h.class == m.class && m.calls.contains(&h.name))
+ .map(|(j, _)| j)
+ })
+ .collect();
+ keep.extend(helpers);
+ keep.sort_unstable();
+ keep.dedup();
+ let functions = keep
+ .into_iter()
+ .map(|i| {
+ hotspot(
+ ctx,
+ &methods[i],
+ total as f64,
+ wall,
+ own.get(&i).copied().unwrap_or(0),
+ incl.get(&i).copied().unwrap_or(0),
+ )
+ })
+ .collect();
+ Ok(Profile { wall, base: ".".into(), functions })
+}
+
+// ------------------------------------------------------------------ editing the source
+
+fn find_body(name: &str, hint: u32) -> impl Fn(&str) -> Option<usize> {
+ let call = format!("{name}(");
+ let spaced = format!("{name} (");
+ move |text: &str| {
+ native::body_line(text, hint, |l| {
+ l.contains("static") && (l.contains(&call) || l.contains(&spaced)) && !l.trim_start().starts_with("//")
+ })
+ }
+}
+
+fn package_line(text: &str) -> String {
+ text.lines().find(|l| l.trim_start().starts_with("package ")).map(|l| l.trim().to_string()).unwrap_or_default()
+}
+
+fn args_array(hs: &Hotspot) -> String {
+ format!("new Object[]{{{}}}", hs.params.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", "))
+}
+
+fn ret(hs: &Hotspot) -> String {
+ hs.returns.clone().unwrap_or_else(|| "Object".into())
+}
+
+fn record_prologue(hs: &Hotspot) -> String {
+ let casts: Vec<String> = hs
+ .params
+ .iter()
+ .enumerate()
+ .map(|(i, p)| format!("({}) __faA[{i}]", p.annotation.as_deref().unwrap_or("Object")))
+ .collect();
+ format!(
+ "if (!FastAnythingRec.inside) {{\n @SuppressWarnings(\"unchecked\") {ret} __faR = ({ret}) FastAnythingRec.record({args}, __faA -> {name}({casts}));\n return __faR;\n}}",
+ ret = ret(hs),
+ args = args_array(hs),
+ name = hs.name,
+ casts = casts.join(", "),
+ )
+}
+
+pub fn record(ctx: &Ctx, java: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
+ let file = ctx.root.join(&hs.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;
+ let rec = REC.replace("/*PACKAGE*/", &package_line(&text)).replace("/*ID*/", &hs.id).replace("/*JSON*/", JSON);
+ let patched = native::insert_in_body(
+ &text,
+ "//",
+ &format!("recording {}", hs.id),
+ &record_prologue(hs),
+ find_body(&hs.name, hs.line),
+ )?;
+ let meta = out.with_extension("meta.json");
+ let mut patches = Patches::new(ctx)?;
+ patches.write(&native::sibling(&file, "FastAnythingRec.java")?, &rec)?;
+ patches.write(&file, &patched)?;
+ let run = output(
+ Command::new(java)
+ .args(args)
+ .current_dir(&ctx.root)
+ .env("FAST_ANYTHING_RECORD_OUT", out)
+ .env("FAST_ANYTHING_RECORD_META", &meta)
+ .env("FAST_ANYTHING_RECORD_LIMIT", limit.to_string())
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null()),
+ "java",
+ );
+ patches.restore()?;
+ 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("the recorder wrote nothing")?)
+ .context("reading the recording summary")
+}
+
+// ------------------------------------------------------------------ the crate
+
+/// Rust type for a Java type.
+pub fn rust_type(t: &str) -> Option<String> {
+ let t = t.replace(' ', "").replace("java.util.", "").replace("java.lang.", "");
+ Some(match t.as_str() {
+ "int" | "Integer" => "i32".into(),
+ "long" | "Long" => "i64".into(),
+ "double" | "Double" => "f64".into(),
+ "float" | "Float" => "f32".into(),
+ "short" | "Short" => "i16".into(),
+ "byte" | "Byte" => "i8".into(),
+ "boolean" | "Boolean" => "bool".into(),
+ "String" => "String".into(),
+ _ if t.ends_with("[]") => format!("Vec<{}>", rust_type(&t[..t.len() - 2])?),
+ _ => {
+ let (raw, inner) = t.strip_suffix('>')?.split_once('<')?;
+ match raw {
+ "List" | "ArrayList" | "Collection" | "LinkedList" => format!("Vec<{}>", rust_type(inner)?),
+ "Map" | "HashMap" | "LinkedHashMap" | "TreeMap" => {
+ format!("std::collections::HashMap<String, {}>", rust_type(inner.strip_prefix("String,")?)?)
+ }
+ _ => return None,
+ }
+ }
+ })
+}
+
+pub const FLAVOR: Flavor = Flavor {
+ lang: backend::Lang::Java,
+ fence: "java",
+ rust_type,
+ default_json: |_| None,
+ rules: &[
+ "Java `int` is `i32` and wraps on overflow: use `wrapping_*` where the original can overflow. `long` is `i64`.",
+ "Java Strings are UTF-16: `length()` and `charAt()` count UTF-16 units. If the code indexes strings, work on `encode_utf16()` (or take a fast path when `is_ascii()`).",
+ "`/` and `%` on integers truncate toward zero, as in Rust. `Math.round` rounds half up: `(x + 0.5).floor()`.",
+ "Arrays and Lists arrive as JSON arrays, Maps as objects with String keys.",
+ ],
+};
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ native::scaffold(ctx, hs, helpers, port, &FLAVOR)
+}
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ native::verify(ctx, port, false)
+}
+
+// ------------------------------------------------------------------ the bridge
+
+fn bridge_class(port: &Port) -> String {
+ format!("FastAnything_{}", util::slug(&port.id))
+}
+
+fn hotspot_of<'a>(ctx: &'a Ctx, port: &Port) -> Result<&'a Hotspot> {
+ ctx.state
+ .hotspots
+ .iter()
+ .find(|h| h.id == port.id)
+ .with_context(|| format!("{} isn't in the last scan: scan again", port.id))
+}
+
+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let hs = hotspot_of(ctx, port)?;
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ let class = bridge_class(port);
+ let (_, lib) = port.lang.artifact(&port.ext);
+ let lib = util::forward_slashes(&ctx.lib_dir().join(lib));
+ let imports: Vec<&str> =
+ text.lines().map(str::trim).filter(|l| l.starts_with("import ") && !l.starts_with("import static ")).collect();
+ let bridge = BRIDGE
+ .replace("/*PACKAGE*/", &package_line(&text))
+ .replace("/*IMPORTS*/", &imports.join("\n"))
+ .replace("/*CLASS*/", &class)
+ .replace("/*RET*/", &ret(hs))
+ .replace("/*LIB*/", &serde_json::to_string(&lib)?)
+ .replace("/*ID*/", &port.id)
+ .replace("/*JSON*/", JSON);
+ let prologue = format!(
+ "if ({class}.ON) {{\n @SuppressWarnings(\"unchecked\") {ret} __faR = ({ret}) {class}.call({args});\n return __faR;\n}}",
+ ret = ret(hs),
+ args = args_array(hs),
+ );
+ let patched = native::insert_in_body(&text, "//", &port.id, &prologue, find_body(&port.func, hs.line))?;
+ fs::write(native::sibling(&file, &format!("{class}.java"))?, bridge)?;
+ 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, native::strip_in_body(&text, "//", &port.id)).with_context(|| format!("writing {}", port.file))?;
+ let bridge = native::sibling(&file, &format!("{}.java", bridge_class(port)))?;
+ if bridge.exists() {
+ fs::remove_file(bridge)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn java_types_map_to_rust() {
+ assert_eq!(rust_type("int[][]").as_deref(), Some("Vec<Vec<i32>>"));
+ assert_eq!(rust_type("List<String>").as_deref(), Some("Vec<String>"));
+ assert_eq!(
+ rust_type("Map<String, List<Double>>").as_deref(),
+ Some("std::collections::HashMap<String, Vec<f64>>")
+ );
+ assert_eq!(rust_type("Point"), None);
+ assert_eq!(
+ entry(&["-Xmx1g".into(), "-cp".into(), "x".into(), "App.java".into(), "a".into()]).unwrap(),
+ "App.java"
+ );
+ assert!(entry(&["-jar".into(), "app.jar".into()]).is_err());
+ assert!(is_java("C:\\jdk\\bin\\java.exe") && !is_java("javac"));
+ }
+}
diff --git a/src/java/Bridge.java b/src/java/Bridge.java
new file mode 100644
index 0000000..6fa5cf6
--- /dev/null
+++ b/src/java/Bridge.java
@@ -0,0 +1,54 @@
+/*PACKAGE*/
+/*IMPORTS*/
+// fast-anything: calls the verified Rust port of /*ID*/. Generated; remove with fast-anything disable /*ID*/
+// FAST_ANYTHING_DISABLE=1 runs the Java version instead. Add --enable-native-access=ALL-UNNAMED to silence Java's notice.
+final class /*CLASS*/ {
+ static /*RET*/ type; // the original's return type, read back with reflection
+ static final java.lang.reflect.Type TYPE;
+ static final java.lang.invoke.MethodHandle CALL, FREE;
+ static final boolean ON;
+
+ static {
+ java.lang.reflect.Type t = Object.class;
+ java.lang.invoke.MethodHandle c = null, f = null;
+ if (System.getenv("FAST_ANYTHING_DISABLE") == null) {
+ try {
+ t = /*CLASS*/.class.getDeclaredField("type").getGenericType();
+ var linker = java.lang.foreign.Linker.nativeLinker();
+ var lib = java.lang.foreign.SymbolLookup.libraryLookup(java.nio.file.Path.of(/*LIB*/), java.lang.foreign.Arena.global());
+ c = linker.downcallHandle(lib.find("fa_call").orElseThrow(), java.lang.foreign.FunctionDescriptor.of(
+ java.lang.foreign.ValueLayout.ADDRESS, java.lang.foreign.ValueLayout.ADDRESS, java.lang.foreign.ValueLayout.JAVA_LONG, java.lang.foreign.ValueLayout.ADDRESS));
+ f = linker.downcallHandle(lib.find("fa_free").orElseThrow(), java.lang.foreign.FunctionDescriptor.ofVoid(
+ java.lang.foreign.ValueLayout.ADDRESS, java.lang.foreign.ValueLayout.JAVA_LONG));
+ } catch (Throwable e) {
+ c = null;
+ }
+ }
+ TYPE = t;
+ CALL = c;
+ FREE = f;
+ ON = c != null;
+ }
+
+ static Object call(Object[] args) {
+ byte[] in = Json.enc(args).getBytes(java.nio.charset.StandardCharsets.UTF_8);
+ try (var arena = java.lang.foreign.Arena.ofConfined()) {
+ var input = arena.allocate(Math.max(1, in.length));
+ java.lang.foreign.MemorySegment.copy(in, 0, input, java.lang.foreign.ValueLayout.JAVA_BYTE, 0, in.length);
+ var len = arena.allocate(java.lang.foreign.ValueLayout.JAVA_LONG);
+ var out = (java.lang.foreign.MemorySegment) CALL.invokeExact(input, (long) in.length, len);
+ long n = len.get(java.lang.foreign.ValueLayout.JAVA_LONG, 0);
+ byte[] bytes = out.reinterpret(n).toArray(java.lang.foreign.ValueLayout.JAVA_BYTE);
+ FREE.invokeExact(out, n);
+ var reply = (java.util.Map<?, ?>) Json.parse(new String(bytes, java.nio.charset.StandardCharsets.UTF_8));
+ if (reply.containsKey("error")) throw new RuntimeException("fast-anything: " + reply.get("error"));
+ return Json.convert(reply.get("ok"), TYPE);
+ } catch (RuntimeException | Error e) {
+ throw e;
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+/*JSON*/
+}
diff --git a/src/java/Describe.java b/src/java/Describe.java
new file mode 100644
index 0000000..21eca12
--- /dev/null
+++ b/src/java/Describe.java
@@ -0,0 +1,176 @@
+// Java side of fast-anything's scan: reads the app's sources with javac's own parser and describes
+// every method. The CLI runs it as java Describe.java <file list> <out.json>. Not meant to be run by hand.
+import com.sun.source.tree.*;
+import com.sun.source.util.*;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.*;
+import java.util.*;
+import javax.lang.model.element.Modifier;
+import javax.tools.*;
+
+public class Describe {
+ static final Set<String> IO = Set.of("System.out", "System.err", "System.in", "System.exit", "System.getenv", "Files",
+ "Paths", "Path", "File", "FileReader", "FileWriter", "BufferedReader", "BufferedWriter", "Scanner", "Socket",
+ "HttpClient", "URL", "Thread", "ProcessBuilder", "Runtime", "PrintStream", "PrintWriter", "FileInputStream",
+ "FileOutputStream", "Console", "Logger", "ExecutorService", "Executors", "CompletableFuture");
+ static final Set<String> NONDET = Set.of("Math.random", "System.nanoTime", "System.currentTimeMillis",
+ "ThreadLocalRandom.current", "Instant.now", "LocalDateTime.now", "LocalDate.now", "LocalTime.now", "UUID.randomUUID",
+ "Clock.systemUTC", "ZonedDateTime.now");
+ static final Set<String> NONDET_NEW = Set.of("Random", "SecureRandom", "SplittableRandom", "Date");
+ static final Set<String> SCALARS = Set.of("int", "long", "double", "float", "boolean", "short", "byte", "Integer",
+ "Long", "Double", "Float", "Boolean", "Short", "Byte", "String");
+ static final Set<String> LISTS = Set.of("List", "ArrayList", "Collection", "LinkedList");
+ static final Set<String> MAPS = Set.of("Map", "HashMap", "LinkedHashMap", "TreeMap");
+
+ static StringBuilder out = new StringBuilder("[");
+ static boolean first = true;
+
+ public static void main(String[] args) throws Exception {
+ List<Path> files = new ArrayList<>();
+ for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) if (!line.isBlank()) files.add(Path.of(line.trim()));
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, StandardCharsets.UTF_8);
+ JavacTask task = (JavacTask) compiler.getTask(null, fm, d -> {}, List.of("-proc:none"), null, fm.getJavaFileObjectsFromPaths(files));
+ SourcePositions pos = Trees.instance(task).getSourcePositions();
+ for (CompilationUnitTree unit : task.parse()) {
+ String src = unit.getSourceFile().getCharContent(true).toString();
+ String pkg = unit.getPackageName() == null ? "" : unit.getPackageName().toString();
+ String path = Path.of(unit.getSourceFile().toUri()).toString();
+ new Unit(unit, src, pos, path).classes(unit.getTypeDecls(), pkg.isEmpty() ? "" : pkg + ".", "");
+ }
+ Files.writeString(Path.of(args[1]), out.append("]").toString(), StandardCharsets.UTF_8);
+ }
+
+ record Unit(CompilationUnitTree unit, String src, SourcePositions pos, String path) {
+ int line(long p) { return (int) unit.getLineMap().getLineNumber(p); }
+ long start(Tree t) { return pos.getStartPosition(unit, t); }
+ long end(Tree t) { return pos.getEndPosition(unit, t); }
+ String text(Tree t) { return t == null ? null : src.substring((int) start(t), (int) end(t)); }
+
+ void classes(List<? extends Tree> decls, String binary, String source) {
+ for (Tree t : decls) {
+ if (!(t instanceof ClassTree ct) || ct.getSimpleName().isEmpty()) continue;
+ String bin = binary + ct.getSimpleName(), own = source + ct.getSimpleName();
+ Set<String> fields = new HashSet<>(), statics = new HashSet<>();
+ for (Tree m : ct.getMembers()) {
+ if (m instanceof VariableTree v) fields.add(v.getName().toString());
+ if (m instanceof MethodTree mt && mt.getModifiers().getFlags().contains(Modifier.STATIC)) statics.add(mt.getName().toString());
+ }
+ for (Tree m : ct.getMembers()) {
+ if (m instanceof MethodTree mt && mt.getBody() != null && mt.getReturnType() != null) method(mt, bin, own, ct.getSimpleName().toString(), fields, statics);
+ else if (m instanceof ClassTree) classes(List.of(m), bin + "$", own + ".");
+ }
+ }
+ }
+
+ void method(MethodTree mt, String bin, String owner, String simple, Set<String> fields, Set<String> statics) {
+ String name = mt.getName().toString();
+ List<String> blockers = new ArrayList<>(), warnings = new ArrayList<>();
+ var flags = mt.getModifiers().getFlags();
+ if (!flags.contains(Modifier.STATIC)) blockers.add("instance method (static methods only for now)");
+ if (name.equals("main")) blockers.add("the entry point");
+ if (!mt.getTypeParameters().isEmpty()) blockers.add("generic method");
+ if (!mt.getThrows().isEmpty()) blockers.add("declares checked exceptions");
+ if (flags.contains(Modifier.SYNCHRONIZED)) blockers.add("synchronized");
+ String returns = text(mt.getReturnType());
+ if (returns.equals("void")) blockers.add("returns nothing (void)");
+ else if (!supported(returns)) blockers.add("returns a " + returns);
+ StringBuilder params = new StringBuilder("[");
+ Set<String> locals = new HashSet<>();
+ for (VariableTree p : mt.getParameters()) {
+ String type = text(p.getType());
+ if (type.contains("...")) blockers.add("takes varargs");
+ else if (!supported(type)) blockers.add("takes a " + type);
+ locals.add(p.getName().toString());
+ if (params.length() > 1) params.append(',');
+ params.append("{\"name\":").append(q(p.getName().toString())).append(",\"annotation\":").append(q(type)).append('}');
+ }
+ params.append(']');
+ Set<String> io = new LinkedHashSet<>(), nondet = new LinkedHashSet<>(), helpers = new LinkedHashSet<>();
+ boolean[] writesStatic = {false};
+ new TreeScanner<Void, Void>() {
+ @Override public Void visitVariable(VariableTree v, Void x) { locals.add(v.getName().toString()); return super.visitVariable(v, x); }
+ @Override public Void visitMethodInvocation(MethodInvocationTree m, Void x) {
+ String sel = m.getMethodSelect().toString();
+ String head = sel.contains(".") ? sel.substring(0, sel.indexOf('.')) : "";
+ String two = sel.lastIndexOf('.') > 0 ? sel.substring(0, sel.lastIndexOf('.')) : "";
+ if (IO.contains(two) || IO.contains(head) || IO.contains(sel)) io.add(sel);
+ if (NONDET.contains(sel)) nondet.add(sel);
+ String bare = sel.startsWith(simple + ".") ? sel.substring(simple.length() + 1) : sel;
+ if (!bare.contains(".") && statics.contains(bare) && !bare.equals(name)) helpers.add(bare);
+ return super.visitMethodInvocation(m, x);
+ }
+ @Override public Void visitMemberSelect(MemberSelectTree m, Void x) {
+ String s = m.toString();
+ if (s.equals("System.in") || s.equals("System.out") || s.equals("System.err")) io.add(s);
+ return super.visitMemberSelect(m, x);
+ }
+ @Override public Void visitNewClass(NewClassTree n, Void x) {
+ String t = n.getIdentifier().toString().replaceAll("<.*", "");
+ if (IO.contains(t)) io.add("new " + t);
+ if (NONDET_NEW.contains(t)) nondet.add("new " + t);
+ return super.visitNewClass(n, x);
+ }
+ void wrote(ExpressionTree target) {
+ if (target instanceof IdentifierTree id && fields.contains(id.getName().toString()) && !locals.contains(id.getName().toString())) writesStatic[0] = true;
+ if (target instanceof MemberSelectTree ms && ms.getExpression().toString().equals(simple) && fields.contains(ms.getIdentifier().toString())) writesStatic[0] = true;
+ }
+ @Override public Void visitAssignment(AssignmentTree a, Void x) { wrote(a.getVariable()); return super.visitAssignment(a, x); }
+ @Override public Void visitCompoundAssignment(CompoundAssignmentTree a, Void x) { wrote(a.getVariable()); return super.visitCompoundAssignment(a, x); }
+ @Override public Void visitUnary(UnaryTree u, Void x) { wrote(u.getExpression()); return super.visitUnary(u, x); }
+ @Override public Void visitLambdaExpression(LambdaExpressionTree l, Void x) { return super.visitLambdaExpression(l, x); }
+ }.scan(mt.getBody(), null);
+ if (!io.isEmpty()) blockers.add("does I/O: " + String.join(", ", io.stream().limit(3).toList()));
+ if (!nondet.isEmpty()) blockers.add("not deterministic: " + String.join(", ", nondet.stream().limit(3).toList()));
+ if (writesStatic[0]) blockers.add("writes static fields");
+ if (!helpers.isEmpty()) warnings.add("calls " + String.join(", ", helpers.stream().limit(3).toList()) + ", they get ported together with it");
+ long brace = start(mt.getBody());
+ int lineEnd = src.indexOf('\n', (int) brace);
+ String after = src.substring((int) brace + 1, lineEnd < 0 ? src.length() : lineEnd).trim();
+ if (!after.isEmpty() && !after.startsWith("//")) blockers.add("its { doesn't end a line (put the body on its own lines)");
+ int line = line(start(mt)), endLine = line(end(mt));
+ String[] lines = src.split("\n", -1);
+ String source = String.join("\n", Arrays.asList(lines).subList(line - 1, Math.min(endLine, lines.length))).stripTrailing().replace("\r", "");
+ if (!first) out.append(',');
+ first = false;
+ out.append("{\"class\":").append(q(bin)).append(",\"owner\":").append(q(owner)).append(",\"name\":").append(q(name))
+ .append(",\"path\":").append(q(path)).append(",\"line\":").append(line).append(",\"end_line\":").append(endLine)
+ .append(",\"params\":").append(params).append(",\"returns\":").append(q(returns))
+ .append(",\"blockers\":").append(list(blockers)).append(",\"warnings\":").append(list(warnings))
+ .append(",\"calls\":").append(list(new ArrayList<>(helpers))).append(",\"source\":").append(q(source)).append('}');
+ }
+ }
+
+ static boolean supported(String t) {
+ t = t.replace(" ", "").replace("java.util.", "").replace("java.lang.", "");
+ if (SCALARS.contains(t)) return true;
+ if (t.endsWith("[]")) return supported(t.substring(0, t.length() - 2));
+ int lt = t.indexOf('<');
+ if (lt < 0 || !t.endsWith(">")) return false;
+ String raw = t.substring(0, lt), inner = t.substring(lt + 1, t.length() - 1);
+ if (LISTS.contains(raw)) return supported(inner);
+ if (MAPS.contains(raw) && inner.startsWith("String,")) return supported(inner.substring(7));
+ return false;
+ }
+
+ static String list(List<String> xs) {
+ StringBuilder b = new StringBuilder("[");
+ for (String x : xs) b.append(b.length() > 1 ? "," : "").append(q(x));
+ return b.append(']').toString();
+ }
+
+ static String q(String s) {
+ StringBuilder b = new StringBuilder("\"");
+ for (char c : s.toCharArray()) {
+ switch (c) {
+ case '"' -> b.append("\\\"");
+ case '\\' -> b.append("\\\\");
+ case '\n' -> b.append("\\n");
+ case '\r' -> b.append("\\r");
+ case '\t' -> b.append("\\t");
+ default -> { if (c < 0x20) b.append(String.format("\\u%04x", (int) c)); else b.append(c); }
+ }
+ }
+ return b.append('"').toString();
+ }
+}
diff --git a/src/java/Json.java b/src/java/Json.java
new file mode 100644
index 0000000..47c89d3
--- /dev/null
+++ b/src/java/Json.java
@@ -0,0 +1,182 @@
+ // ---- JSON, shared by the recorder and the bridge (generated by fast-anything)
+ static final class Json {
+ static final class Unsupported extends RuntimeException {
+ Unsupported(String m) { super(m, null, false, false); }
+ }
+
+ static String enc(Object v) {
+ StringBuilder b = new StringBuilder();
+ enc(v, b);
+ return b.toString();
+ }
+
+ static void enc(Object v, StringBuilder b) {
+ if (v == null) b.append("null");
+ else if (v instanceof Boolean || v instanceof Integer || v instanceof Long || v instanceof Short || v instanceof Byte) b.append(v);
+ else if (v instanceof Double || v instanceof Float) {
+ double d = ((Number) v).doubleValue();
+ if (!Double.isFinite(d)) throw new Unsupported("NaN or Infinity");
+ b.append(v);
+ } else if (v instanceof String s) str(s, b);
+ else if (v.getClass().isArray()) {
+ b.append('[');
+ for (int i = 0, n = java.lang.reflect.Array.getLength(v); i < n; i++) {
+ if (i > 0) b.append(',');
+ enc(java.lang.reflect.Array.get(v, i), b);
+ }
+ b.append(']');
+ } else if (v instanceof java.util.List<?> l) {
+ b.append('[');
+ boolean first = true;
+ for (Object x : l) {
+ if (!first) b.append(',');
+ first = false;
+ enc(x, b);
+ }
+ b.append(']');
+ } else if (v instanceof java.util.Map<?, ?> m) {
+ b.append('{');
+ boolean first = true;
+ for (var e : m.entrySet()) {
+ if (!(e.getKey() instanceof String k)) throw new Unsupported("Map with non-String keys");
+ if (!first) b.append(',');
+ first = false;
+ str(k, b);
+ b.append(':');
+ enc(e.getValue(), b);
+ }
+ b.append('}');
+ } else throw new Unsupported(v.getClass().getSimpleName());
+ }
+
+ static void str(String s, StringBuilder b) {
+ b.append('"');
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (Character.isHighSurrogate(c) && i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1))) {
+ b.append(c).append(s.charAt(++i));
+ continue;
+ }
+ if (Character.isSurrogate(c)) throw new Unsupported("String with a lone surrogate");
+ switch (c) {
+ case '"' -> b.append("\\\"");
+ case '\\' -> b.append("\\\\");
+ case '\n' -> b.append("\\n");
+ case '\r' -> b.append("\\r");
+ case '\t' -> b.append("\\t");
+ default -> { if (c < 0x20) b.append(String.format("\\u%04x", (int) c)); else b.append(c); }
+ }
+ }
+ b.append('"');
+ }
+
+ static String str(String s) {
+ StringBuilder b = new StringBuilder();
+ str(s, b);
+ return b.toString();
+ }
+
+ static Object parse(String s) {
+ int[] i = {0};
+ return value(s, i);
+ }
+
+ static void ws(String s, int[] i) {
+ while (i[0] < s.length() && Character.isWhitespace(s.charAt(i[0]))) i[0]++;
+ }
+
+ static Object value(String s, int[] i) {
+ ws(s, i);
+ char c = s.charAt(i[0]);
+ if (c == '{') {
+ java.util.Map<String, Object> m = new java.util.LinkedHashMap<>();
+ i[0]++;
+ ws(s, i);
+ if (s.charAt(i[0]) == '}') { i[0]++; return m; }
+ while (true) {
+ ws(s, i);
+ String k = (String) value(s, i);
+ ws(s, i);
+ i[0]++; // :
+ m.put(k, value(s, i));
+ ws(s, i);
+ if (s.charAt(i[0]++) == '}') return m;
+ }
+ }
+ if (c == '[') {
+ java.util.List<Object> l = new java.util.ArrayList<>();
+ i[0]++;
+ ws(s, i);
+ if (s.charAt(i[0]) == ']') { i[0]++; return l; }
+ while (true) {
+ l.add(value(s, i));
+ ws(s, i);
+ if (s.charAt(i[0]++) == ']') return l;
+ }
+ }
+ if (c == '"') {
+ StringBuilder b = new StringBuilder();
+ i[0]++;
+ while (true) {
+ char d = s.charAt(i[0]++);
+ if (d == '"') return b.toString();
+ if (d != '\\') { b.append(d); continue; }
+ char e = s.charAt(i[0]++);
+ switch (e) {
+ case 'n' -> b.append('\n');
+ case 'r' -> b.append('\r');
+ case 't' -> b.append('\t');
+ case 'b' -> b.append('\b');
+ case 'f' -> b.append('\f');
+ case 'u' -> { b.append((char) Integer.parseInt(s.substring(i[0], i[0] + 4), 16)); i[0] += 4; }
+ default -> b.append(e);
+ }
+ }
+ }
+ if (s.startsWith("true", i[0])) { i[0] += 4; return Boolean.TRUE; }
+ if (s.startsWith("false", i[0])) { i[0] += 5; return Boolean.FALSE; }
+ if (s.startsWith("null", i[0])) { i[0] += 4; return null; }
+ int start = i[0];
+ while (i[0] < s.length() && "+-0123456789.eE".indexOf(s.charAt(i[0])) >= 0) i[0]++;
+ String num = s.substring(start, i[0]);
+ if (num.contains(".") || num.contains("e") || num.contains("E")) return Double.parseDouble(num);
+ try { return Long.parseLong(num); } catch (NumberFormatException ex) { return Double.parseDouble(num); }
+ }
+
+ /** A parsed JSON value as the Java type t (from the original method's signature). */
+ static Object convert(Object v, java.lang.reflect.Type t) {
+ if (v == null) return null;
+ if (t instanceof Class<?> c) {
+ if (c == int.class || c == Integer.class) return ((Number) v).intValue();
+ if (c == long.class || c == Long.class) return ((Number) v).longValue();
+ if (c == double.class || c == Double.class) return ((Number) v).doubleValue();
+ if (c == float.class || c == Float.class) return ((Number) v).floatValue();
+ if (c == short.class || c == Short.class) return ((Number) v).shortValue();
+ if (c == byte.class || c == Byte.class) return ((Number) v).byteValue();
+ if (c.isArray()) {
+ java.util.List<?> l = (java.util.List<?>) v;
+ Object a = java.lang.reflect.Array.newInstance(c.getComponentType(), l.size());
+ for (int i = 0; i < l.size(); i++) java.lang.reflect.Array.set(a, i, convert(l.get(i), c.getComponentType()));
+ return a;
+ }
+ if (c == java.util.TreeMap.class) return new java.util.TreeMap<>((java.util.Map<?, ?>) v);
+ if (c == java.util.HashMap.class) return new java.util.HashMap<>((java.util.Map<?, ?>) v);
+ if (c == java.util.LinkedList.class) return new java.util.LinkedList<>((java.util.List<?>) v);
+ return v;
+ }
+ if (t instanceof java.lang.reflect.ParameterizedType p) {
+ Class<?> raw = (Class<?>) p.getRawType();
+ java.lang.reflect.Type[] a = p.getActualTypeArguments();
+ if (java.util.Map.class.isAssignableFrom(raw)) {
+ java.util.Map<String, Object> m = raw == java.util.TreeMap.class ? new java.util.TreeMap<>()
+ : raw == java.util.HashMap.class ? new java.util.HashMap<>() : new java.util.LinkedHashMap<>();
+ for (var e : ((java.util.Map<?, ?>) v).entrySet()) m.put((String) e.getKey(), convert(e.getValue(), a[1]));
+ return m;
+ }
+ java.util.List<Object> l = raw == java.util.LinkedList.class ? new java.util.LinkedList<>() : new java.util.ArrayList<>();
+ for (Object x : (java.util.List<?>) v) l.add(convert(x, a[0]));
+ return l;
+ }
+ return v;
+ }
+ }
diff --git a/src/java/Rec.java b/src/java/Rec.java
new file mode 100644
index 0000000..493b426
--- /dev/null
+++ b/src/java/Rec.java
@@ -0,0 +1,156 @@
+/*PACKAGE*/
+// fast-anything: records calls to /*ID*/ for one run. Generated; removed when the run ends.
+final class FastAnythingRec {
+ static boolean inside;
+ static final int LIMIT = Integer.parseInt(System.getenv().getOrDefault("FAST_ANYTHING_RECORD_LIMIT", "500"));
+ static final java.util.Random RNG = new java.util.Random(0xFA57);
+ static final java.util.List<String> kept = new java.util.ArrayList<>();
+ static final java.util.List<Object[]> keptArgs = new java.util.ArrayList<>();
+ static final java.util.Set<String> unsupported = new java.util.LinkedHashSet<>();
+ static long calls, skipped, nanos;
+ static java.util.function.Function<Object[], Object> fn;
+
+ static {
+ Runtime.getRuntime().addShutdownHook(new Thread(FastAnythingRec::save));
+ }
+
+ static synchronized Object record(Object[] args, java.util.function.Function<Object[], Object> f) {
+ fn = f;
+ inside = true;
+ try {
+ calls++;
+ int slot = kept.size() < LIMIT ? kept.size() : (int) (RNG.nextDouble() * calls);
+ String a = null;
+ Object[] copy = null;
+ if (slot < LIMIT) {
+ try {
+ a = Json.enc(args);
+ copy = (Object[]) deepCopy(args);
+ } catch (Json.Unsupported e) {
+ skipped++;
+ unsupported.add(e.getMessage());
+ }
+ }
+ long t = System.nanoTime();
+ Object r;
+ try {
+ r = f.apply(args);
+ } catch (RuntimeException | Error e) {
+ nanos += System.nanoTime() - t;
+ if (a != null) store(slot, "{\"args\":" + a + ",\"raises\":" + Json.str(e.getClass().getName()) + "}", null);
+ throw e;
+ }
+ nanos += System.nanoTime() - t;
+ if (a != null) {
+ try {
+ store(slot, "{\"args\":" + a + ",\"result\":" + Json.enc(r) + "}", copy);
+ } catch (Json.Unsupported e) {
+ skipped++;
+ unsupported.add(e.getMessage());
+ }
+ }
+ return r;
+ } finally {
+ inside = false;
+ }
+ }
+
+ static void store(int slot, String line, Object[] args) {
+ if (slot < kept.size()) {
+ kept.set(slot, line);
+ keptArgs.set(slot, args);
+ } else {
+ kept.add(line);
+ keptArgs.add(args);
+ }
+ }
+
+ static Object deepCopy(Object v) {
+ if (v == null) return null;
+ if (v.getClass().isArray()) {
+ int n = java.lang.reflect.Array.getLength(v);
+ Object c = java.lang.reflect.Array.newInstance(v.getClass().getComponentType(), n);
+ for (int i = 0; i < n; i++) java.lang.reflect.Array.set(c, i, deepCopy(java.lang.reflect.Array.get(v, i)));
+ return c;
+ }
+ if (v instanceof java.util.List<?> l) {
+ java.util.List<Object> c = v instanceof java.util.LinkedList ? new java.util.LinkedList<>() : new java.util.ArrayList<>();
+ for (Object x : l) c.add(deepCopy(x));
+ return c;
+ }
+ if (v instanceof java.util.Map<?, ?> m) {
+ java.util.Map<Object, Object> c = v instanceof java.util.TreeMap ? new java.util.TreeMap<>()
+ : v instanceof java.util.LinkedHashMap ? new java.util.LinkedHashMap<>() : new java.util.HashMap<>();
+ for (var e : m.entrySet()) c.put(e.getKey(), deepCopy(e.getValue()));
+ return c;
+ }
+ return v;
+ }
+
+ static final int[] SLICES = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55};
+
+ static java.util.List<Object> variants(Object v) {
+ java.util.List<Object> out = new java.util.ArrayList<>();
+ int n = v instanceof String s ? s.codePointCount(0, s.length())
+ : v != null && v.getClass().isArray() ? java.lang.reflect.Array.getLength(v)
+ : v instanceof java.util.List<?> l ? l.size() : 0;
+ if (n < 2) return out;
+ for (int len : SLICES) {
+ if (len >= n) break;
+ for (int rep = 0; rep < (len < 2 ? 1 : 3); rep++) {
+ int off = RNG.nextInt(n - len + 1);
+ if (v instanceof String s) {
+ out.add(new String(s.codePoints().skip(off).limit(len).toArray(), 0, len));
+ } else if (v instanceof java.util.List<?> l) {
+ out.add(deepCopy(new java.util.ArrayList<>(l.subList(off, off + len))));
+ } else {
+ Object c = java.lang.reflect.Array.newInstance(v.getClass().getComponentType(), len);
+ System.arraycopy(v, off, c, 0, len);
+ out.add(deepCopy(c));
+ }
+ }
+ }
+ return out;
+ }
+
+ static synchronized void save() {
+ inside = true;
+ java.util.List<String> derived = new java.util.ArrayList<>();
+ java.util.Set<String> seen = new java.util.HashSet<>();
+ long start = System.nanoTime();
+ outer:
+ for (Object[] args : keptArgs) {
+ if (args == null || fn == null) continue;
+ for (int i = 0; i < args.length; i++) {
+ for (Object smaller : variants(args[i])) {
+ if (derived.size() >= 200 || System.nanoTime() - start > 3_000_000_000L) break outer;
+ Object[] next = (Object[]) deepCopy(args);
+ next[i] = smaller;
+ try {
+ String a = Json.enc(next);
+ if (!seen.add(a)) continue;
+ Object r = fn.apply(next);
+ derived.add("{\"args\":" + a + ",\"result\":" + Json.enc(r) + ",\"derived\":true}");
+ } catch (Throwable e) {
+ // outside the function's domain: not a fair test
+ }
+ }
+ }
+ }
+ try {
+ StringBuilder b = new StringBuilder();
+ for (String line : kept) b.append(line).append('\n');
+ for (String line : derived) b.append(line).append('\n');
+ java.nio.file.Files.writeString(java.nio.file.Path.of(System.getenv("FAST_ANYTHING_RECORD_OUT")), b, java.nio.charset.StandardCharsets.UTF_8);
+ StringBuilder u = new StringBuilder("[");
+ for (String s : unsupported) u.append(u.length() > 1 ? "," : "").append(Json.str(s));
+ String meta = "{\"calls\":" + calls + ",\"kept\":" + kept.size() + ",\"skipped\":" + skipped + ",\"unsupported\":" + u + "]"
+ + ",\"original_ns\":" + (calls > 0 ? (double) nanos / calls : 0) + "}";
+ java.nio.file.Files.writeString(java.nio.file.Path.of(System.getenv("FAST_ANYTHING_RECORD_META")), meta, java.nio.charset.StandardCharsets.UTF_8);
+ } catch (java.io.IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+/*JSON*/
+}
diff --git a/src/main.rs b/src/main.rs
index 0b00c4a..e9506bf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,8 +4,11 @@ mod agent;
mod backend;
mod bench;
mod doctor;
+mod golang;
mod hotspot;
+mod java;
mod mcp;
+mod native;
mod node;
mod pipeline;
mod python;
@@ -100,6 +103,9 @@ enum Cmd {
Doctor,
/// Run as an MCP server on stdio (for Claude Code, Codex, Cursor, ...)
Mcp,
+ /// Replays recorded calls against a C-bridge port (used by verify, in its own process)
+ #[command(name = "__replay", hide = true)]
+ Replay { job: PathBuf },
}
fn main() -> ExitCode {
@@ -115,8 +121,10 @@ fn main() -> ExitCode {
}
fn run(cmd: Cmd, root: &Path) -> Result<()> {
- if matches!(cmd, Cmd::Mcp) {
- return mcp::serve();
+ match cmd {
+ Cmd::Mcp => return mcp::serve(),
+ Cmd::Replay { job } => return native::replay(&job),
+ _ => {}
}
ui::banner();
match cmd {
@@ -174,6 +182,6 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {
Ok(())
}
Cmd::Doctor => doctor::run(),
- Cmd::Mcp => unreachable!(),
+ Cmd::Mcp | Cmd::Replay { .. } => unreachable!(),
}
}
diff --git a/src/mcp.rs b/src/mcp.rs
index 9354a22..a2ebd5c 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -8,7 +8,7 @@ use std::path::PathBuf;
const PROTOCOL: &str = "2025-06-18";
-const INSTRUCTIONS: &str = "fast-anything speeds up Python, Node.js and Ruby apps by porting their hottest pure functions to Rust (PyO3 / napi-rs / C ABI) \
+const INSTRUCTIONS: &str = "fast-anything speeds up Python, Node.js, Ruby, Java and Go apps by porting their hottest pure functions to Rust (PyO3 / napi-rs / a C ABI bridge) \
and proving the port gives the same results on real recorded calls. Loop: fast_scan -> fast_port -> write src/lib.rs \
following the returned task -> fast_verify (repeat until it passes) -> fast_enable -> fast_bench -> fast_report.";
@@ -23,7 +23,7 @@ fn tools() -> Value {
tool(
"fast_scan",
"Run the app under a profiler and rank functions by time share and portability to Rust.",
- json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"node\", \"app.js\"]" }, "path": path }),
+ json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "path": path }),
json!(["command"])
),
tool(
@@ -46,13 +46,13 @@ fn tools() -> Value {
),
tool(
"fast_disable",
- "Switch a function back to the original Python.",
+ "Switch a function back to the original code.",
json!({ "id": id, "path": path }),
json!([])
),
tool(
"fast_bench",
- "Time the whole app: original Python vs Rust ports.",
+ "Time the whole app: original code vs Rust ports.",
json!({ "runs": { "type": "integer", "default": 5 }, "path": path }),
json!([])
),
diff --git a/src/native.rs b/src/native.rs
new file mode 100644
index 0000000..53b9f06
--- /dev/null
+++ b/src/native.rs
@@ -0,0 +1,598 @@
+//! The bridge shared by every language that calls its port through a C entry point (Ruby, Go,
+//! PHP, Java): the crate (JSON in, JSON out), the replay check, temporary edits that always get
+//! undone, and the blocks fast-anything puts inside a function's body.
+//!
+//! Go, PHP and Java record differently from Python and Node: a few lines at the top of the hot
+//! function hand each call to a recorder, which also answers the shrunk "derived" inputs at exit.
+//! Verifying then needs no interpreter at all: fast-anything loads the port itself and replays
+//! the file, in a child process so a crashing port can't take it down.
+
+use crate::backend::{self, Lang};
+use crate::hotspot::Hotspot;
+use crate::state::{Ctx, Failure, Micro, Port, Verify};
+use crate::util::{self, combined, output, tail};
+use anyhow::{Context, Result, bail};
+use serde::Deserialize;
+use serde_json::{Value, json};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::time::Instant;
+
+/// What changes from one C-bridge language to the next.
+pub struct Flavor {
+ pub lang: Lang,
+ /// Code fence language for TASK.md.
+ pub fence: &'static str,
+ /// Rust type for a type written in the original language.
+ pub rust_type: fn(&str) -> Option<String>,
+ /// A default value in the original language, as JSON.
+ pub default_json: fn(&str) -> Option<String>,
+ /// Language-specific rules for TASK.md.
+ pub rules: &'static [&'static str],
+}
+
+// ------------------------------------------------------------------ the crate
+
+pub fn snake(name: &str) -> String {
+ let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
+ match s.as_str() {
+ "type" | "match" | "fn" | "ref" | "move" | "loop" | "mod" | "use" | "impl" | "self" | "box" | "gen" | "in"
+ | "where" | "trait" | "struct" | "enum" | "crate" | "super" | "unsafe" | "async" | "await" | "dyn" => {
+ format!("r#{s}")
+ }
+ _ => s,
+ }
+}
+
+pub fn glue_rs(hs: &Hotspot, port: &Port, default_json: fn(&str) -> Option<String>) -> String {
+ let args: Vec<String> = hs
+ .params
+ .iter()
+ .enumerate()
+ .map(|(i, p)| match p.default.as_deref().and_then(default_json) {
+ Some(d) => format!("arg(&args, {i}, Some({d:?}))?"),
+ None => format!("arg(&args, {i}, None)?"),
+ })
+ .collect();
+ format!(
+ "//! C entry point generated by fast-anything: JSON array of arguments in, {{\"ok\": result}} or\n\
+ //! {{\"error\": message}} out. Don't edit this file; the port lives in src/port.rs.\n\n\
+ mod port;\n\n\
+ use serde_json::{{Value, json}};\n\n\
+ fn arg<T: serde::de::DeserializeOwned>(args: &[Value], i: usize, default: Option<&str>) -> Result<T, String> {{\n \
+ match args.get(i) {{\n \
+ Some(v) => T::deserialize(v).map_err(|e| format!(\"argument {{}}: {{e}}\", i + 1)),\n \
+ None => match default {{\n \
+ Some(d) => serde_json::from_str(d).map_err(|e| e.to_string()),\n \
+ None => Err(format!(\"missing argument {{}}\", i + 1)),\n \
+ }},\n \
+ }}\n\
+ }}\n\n\
+ fn call(input: &[u8]) -> Result<Value, String> {{\n \
+ let args: Vec<Value> = serde_json::from_slice(input).map_err(|e| e.to_string())?;\n \
+ let result = port::{func}({args})?;\n \
+ serde_json::to_value(result).map_err(|e| e.to_string())\n\
+ }}\n\n\
+ /// # Safety\n\
+ /// input must point to len readable bytes and out_len to a writable usize.\n\
+ #[unsafe(no_mangle)]\n\
+ pub unsafe extern \"C\" fn fa_call(input: *const u8, len: usize, out_len: *mut usize) -> *mut u8 {{\n \
+ let input = unsafe {{ std::slice::from_raw_parts(input, len) }};\n \
+ let reply = match std::panic::catch_unwind(|| call(input)) {{\n \
+ Ok(Ok(value)) => json!({{ \"ok\": value }}),\n \
+ Ok(Err(message)) => json!({{ \"error\": message }}),\n \
+ Err(panic) => {{\n \
+ let text = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());\n \
+ json!({{ \"error\": format!(\"panic: {{}}\", text.unwrap_or_default()) }})\n \
+ }}\n \
+ }};\n \
+ let bytes = serde_json::to_vec(&reply).unwrap_or_default().into_boxed_slice();\n \
+ unsafe {{ *out_len = bytes.len() }};\n \
+ Box::into_raw(bytes) as *mut u8\n\
+ }}\n\n\
+ /// # Safety\n\
+ /// ptr and len must come from fa_call.\n\
+ #[unsafe(no_mangle)]\n\
+ pub unsafe extern \"C\" fn fa_free(ptr: *mut u8, len: usize) {{\n \
+ if !ptr.is_null() {{\n \
+ drop(unsafe {{ Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr, len)) }});\n \
+ }}\n\
+ }}\n",
+ func = snake(&hs.name),
+ args = args.join(", "),
+ ) + &format!("\n// {}\n", port.id)
+}
+
+pub fn cargo_toml(port: &Port) -> String {
+ format!(
+ "# Rust port of {id}, generated by fast-anything.\n\
+ [package]\nname = \"{ext}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\n\
+ [lib]\nname = \"{ext}\"\ncrate-type = [\"cdylib\"]\n\n\
+ [dependencies]\nserde = {{ version = \"1\", features = [\"derive\"] }}\nserde_json = \"1\"\n\n{profile}",
+ id = port.id,
+ ext = port.ext,
+ profile = backend::RELEASE_PROFILE,
+ )
+}
+
+/// The stub the agent fills in, typed from the original signature where the types are known.
+pub fn port_rs(hs: &Hotspot, port: &Port, f: &Flavor) -> String {
+ let ty = |t: Option<&str>| t.and_then(f.rust_type).unwrap_or_else(|| "serde_json::Value".to_string());
+ let params: Vec<String> =
+ hs.params.iter().map(|p| format!("{}: {}", snake(&p.name), ty(p.annotation.as_deref()))).collect();
+ format!(
+ "//! Rust port of {id} ({file}:{line}), generated by fast-anything.\n\
+ //! Replace the todo!() with a faithful, fast port. Arguments arrive already deserialized; change the\n\
+ //! types if the recorded calls need others. Return Err(message) where {label} would fail.\n\
+ //! Check it with: fast-anything verify {id}\n\
+ #![allow(non_snake_case)]\n\n\
+ #[allow(unused_variables)]\n\
+ pub fn {func}({params}) -> Result<{ret}, String> {{\n todo!(\"port {id}\")\n}}\n",
+ id = port.id,
+ file = hs.file,
+ line = hs.line,
+ label = f.lang.label(),
+ func = snake(&hs.name),
+ params = params.join(", "),
+ ret = ty(hs.returns.as_deref()),
+ )
+}
+
+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())
+ .filter(|c| c.get("derived").is_none())
+ .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!("fails with {}", e.as_str().unwrap_or("an 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, f: &Flavor) -> String {
+ let fence = "```";
+ let label = f.lang.label();
+ 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(&format!(
+ "## Helpers it calls\n\nPort these as private Rust functions in src/port.rs (they stay in {label} 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}{}\n{}\n{fence}\n\n", f.fence, h.source)),
+ None => helper_md.push_str(&format!("- `{name}`: read it in {}\n", hs.file)),
+ }
+ }
+ }
+ let rules: String = f.rules.iter().map(|r| format!("- {r}\n")).collect();
+ 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 {label} below, and runs fast.\n\
+`src/lib.rs` is generated glue (JSON in, JSON out through a C entry point): don't edit it.\n\
+Only edit files in this folder. Don't touch the {label} project.\n\n\
+## The original ({file}:{line})\n\n{fence}{lang}\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. A few:\n\n{fence}\n{samples}\n{fence}\n\n\
+## Rules\n\n\
+- Same result for every input, edge cases included: empty input, zero, negatives, unicode.\n\
+{rules}\
+- Return `Err(message)` where the original would fail.\n\
+- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases. Threads are fine if the result is the same.\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,
+ lang = f.fence,
+ source = hs.source,
+ recorded = port.recorded,
+ seen = util::thousands(port.calls_seen),
+ )
+}
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port, f: &Flavor) -> 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"), glue_rs(hs, port, f.default_json))?;
+ let body = dir.join("src/port.rs");
+ if !body.exists() {
+ fs::write(&body, port_rs(hs, port, f))?;
+ }
+ let task = task_md(hs, helpers, port, &dir, f);
+ fs::write(dir.join("TASK.md"), &task)?;
+ Ok(task)
+}
+
+// ------------------------------------------------------------------ replay
+
+#[derive(Deserialize)]
+struct ReplayJob {
+ lib: PathBuf,
+ cases: PathBuf,
+ meta: PathBuf,
+ func: String,
+ out: PathBuf,
+ /// Go: a nil slice or map records as null; the port's empty Vec is the same thing.
+ #[serde(default)]
+ loose_empty: bool,
+ #[serde(default = "half")]
+ budget: f64,
+}
+
+fn half() -> f64 {
+ 0.5
+}
+
+/// Build-and-check for C-bridge ports: replays the recordings in a child process.
+pub fn verify(ctx: &Ctx, port: &Port, loose_empty: bool) -> Result<Verify> {
+ let dir = ctx.crate_dir(port);
+ let (_, lib) = port.lang.artifact(&port.ext);
+ let out = dir.join("verify.json");
+ let _ = fs::remove_file(&out);
+ let job = json!({
+ "lib": ctx.lib_dir().join(lib), "cases": dir.join("recordings.jsonl"), "meta": dir.join("recordings.meta.json"),
+ "func": port.func, "out": out, "loose_empty": loose_empty,
+ });
+ let job_path = dir.join("job-verify.json");
+ fs::write(&job_path, serde_json::to_vec_pretty(&job)?)?;
+ let me = std::env::current_exe().context("finding fast-anything itself")?;
+ let run = output(Command::new(me).arg("__replay").arg(&job_path), "fast-anything")?;
+ let mut v = if run.status.success() && out.exists() {
+ serde_json::from_str::<Verify>(&fs::read_to_string(&out)?).context("reading verify results")?
+ } else {
+ let total = fs::read_to_string(dir.join("recordings.jsonl")).map(|t| t.lines().count()).unwrap_or(0);
+ Verify {
+ total,
+ failed: total,
+ failures: vec![Failure {
+ case: 0,
+ call: format!("{}(...) (replaying the recorded calls)", port.func),
+ expected: "the same results".into(),
+ got: format!("the port crashed ({}): {}", run.status, tail(&combined(&run), 12)),
+ }],
+ ..Verify::default()
+ }
+ };
+ v.built = true;
+ Ok(v)
+}
+
+type FaCall = unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8;
+type FaFree = unsafe extern "C" fn(*mut u8, usize);
+
+fn show(v: &Value, limit: usize) -> String {
+ let s = v.to_string();
+ if s.chars().count() <= limit { s } else { format!("{}…", s.chars().take(limit - 1).collect::<String>()) }
+}
+
+/// The hidden fast-anything __replay <job> command.
+pub fn replay(job_path: &Path) -> Result<()> {
+ let job: ReplayJob = serde_json::from_str(&fs::read_to_string(job_path)?).context("reading the replay job")?;
+ // SAFETY: the library is the port fast-anything just built; its two entry points have these signatures.
+ let lib =
+ unsafe { libloading::Library::new(&job.lib) }.with_context(|| format!("loading {}", job.lib.display()))?;
+ let call: libloading::Symbol<FaCall> = unsafe { lib.get(b"fa_call") }.context("fa_call missing")?;
+ let free: libloading::Symbol<FaFree> = unsafe { lib.get(b"fa_free") }.context("fa_free missing")?;
+ let invoke = |input: &[u8]| -> std::result::Result<Value, String> {
+ let mut n = 0usize;
+ let bytes = unsafe {
+ let p = call(input.as_ptr(), input.len(), &mut n);
+ let bytes = std::slice::from_raw_parts(p, n).to_vec();
+ free(p, n);
+ bytes
+ };
+ let reply: Value = serde_json::from_slice(&bytes).map_err(|e| format!("bad reply: {e}"))?;
+ match reply.get("error") {
+ Some(e) => Err(e.as_str().map(str::to_string).unwrap_or_else(|| e.to_string())),
+ None => Ok(reply.get("ok").cloned().unwrap_or(Value::Null)),
+ }
+ };
+
+ let text = fs::read_to_string(&job.cases).context("reading recordings.jsonl")?;
+ let cases: Vec<Value> =
+ text.lines().filter(|l| !l.trim().is_empty()).filter_map(|l| serde_json::from_str(l).ok()).collect();
+ let (mut passed, mut failed, mut derived) = (0, 0, 0);
+ let mut failures = Vec::new();
+ let mut inputs = Vec::new();
+ for (i, case) in cases.iter().enumerate() {
+ let input = serde_json::to_vec(&case["args"])?;
+ let is_derived = case.get("derived").is_some();
+ if is_derived {
+ derived += 1;
+ } else {
+ inputs.push(input.clone());
+ }
+ let got = invoke(&input);
+ let (ok, expected) = match case.get("raises") {
+ Some(e) => (got.is_err(), format!("fails with {}", e.as_str().unwrap_or("an error"))),
+ None => {
+ let want = &case["result"];
+ (got.as_ref().is_ok_and(|g| same(want, g, job.loose_empty)), show(want, 160))
+ }
+ };
+ if ok {
+ passed += 1;
+ continue;
+ }
+ failed += 1;
+ if failures.len() < 8 {
+ let args: Vec<String> =
+ case["args"].as_array().map(|a| a.iter().map(|v| show(v, 80)).collect()).unwrap_or_default();
+ failures.push(Failure {
+ case: i,
+ call: format!("{}{}({})", if is_derived { "(derived) " } else { "" }, job.func, args.join(", ")),
+ expected,
+ got: match got {
+ Ok(v) => show(&v, 160),
+ Err(e) => format!("error: {}", show(&Value::String(e), 200)),
+ },
+ });
+ }
+ }
+
+ let mut v = Verify { total: cases.len(), derived, passed, failed, failures, ..Verify::default() };
+ let original_ns = fs::read_to_string(&job.meta)
+ .ok()
+ .and_then(|t| serde_json::from_str::<Value>(&t).ok())
+ .and_then(|m| m["original_ns"].as_f64());
+ if let Some(original_ns) = original_ns.filter(|n| *n > 0.0 && failed == 0 && !inputs.is_empty()) {
+ {
+ let (mut best, mut spent, mut passes) = (f64::INFINITY, 0.0, 0);
+ while passes < 3 || (spent < job.budget && passes < 2000) {
+ let t = Instant::now();
+ for input in &inputs {
+ let _ = std::hint::black_box(invoke(input));
+ }
+ let took = t.elapsed().as_secs_f64();
+ best = best.min(took);
+ spent += took;
+ passes += 1;
+ }
+ let rust_ns = best / inputs.len() as f64 * 1e9;
+ v.micro =
+ Some(Micro { original_ns, rust_ns, speedup: if rust_ns > 0.0 { original_ns / rust_ns } else { 0.0 } });
+ }
+ }
+ fs::write(&job.out, serde_json::to_vec(&v)?)?;
+ Ok(())
+}
+
+/// Same value, give or take float rounding.
+pub fn same(a: &Value, b: &Value, loose_empty: bool) -> bool {
+ match (a, b) {
+ (Value::Number(x), Value::Number(y)) => {
+ if x.is_f64() || y.is_f64() {
+ let (x, y) = (x.as_f64().unwrap_or(f64::NAN), y.as_f64().unwrap_or(f64::NAN));
+ x == y || (x - y).abs() <= f64::max(1e-12, 1e-9 * x.abs().max(y.abs()))
+ } else {
+ x == y
+ }
+ }
+ (Value::Array(x), Value::Array(y)) => {
+ x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q, loose_empty))
+ }
+ (Value::Object(x), Value::Object(y)) => {
+ x.len() == y.len() && x.iter().all(|(k, p)| y.get(k).is_some_and(|q| same(p, q, loose_empty)))
+ }
+ (Value::Null, Value::Array(v)) | (Value::Array(v), Value::Null) => loose_empty && v.is_empty(),
+ (Value::Null, Value::Object(v)) | (Value::Object(v), Value::Null) => loose_empty && v.is_empty(),
+ _ => a == b,
+ }
+}
+
+// ------------------------------------------------------------------ temporary edits
+
+/// Files changed (or created) for one run. Everything goes back on restore() or drop, and a copy
+/// sits in .fast/backup until then, so even a killed run is undone by the next one.
+pub struct Patches {
+ dir: PathBuf,
+ files: Vec<(PathBuf, Option<String>)>,
+}
+
+impl Patches {
+ pub fn new(ctx: &Ctx) -> Result<Patches> {
+ let dir = ctx.fast.join("backup");
+ restore_leftovers(&dir)?;
+ fs::create_dir_all(&dir)?;
+ Ok(Patches { dir, files: Vec::new() })
+ }
+
+ fn track(&mut self, path: &Path) -> Result<()> {
+ if self.files.iter().any(|(p, _)| p == path) {
+ return Ok(());
+ }
+ let original = if path.exists() {
+ Some(fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?)
+ } else {
+ None
+ };
+ let n = self.files.len();
+ fs::write(self.dir.join(format!("{n}.path")), path.to_string_lossy().as_bytes())?;
+ if let Some(text) = &original {
+ fs::write(self.dir.join(format!("{n}.orig")), text)?;
+ }
+ self.files.push((path.to_path_buf(), original));
+ Ok(())
+ }
+
+ pub fn write(&mut self, path: &Path, text: &str) -> Result<()> {
+ self.track(path)?;
+ fs::write(path, text).with_context(|| format!("writing {}", path.display()))
+ }
+
+ pub fn restore(&mut self) -> Result<()> {
+ let mut first_err = None;
+ for (path, original) in self.files.drain(..).rev() {
+ let r = match original {
+ Some(text) => fs::write(&path, text),
+ None => fs::remove_file(&path)
+ .or_else(|e| if e.kind() == std::io::ErrorKind::NotFound { Ok(()) } else { Err(e) }),
+ };
+ if let Err(e) = r {
+ first_err.get_or_insert(anyhow::anyhow!(
+ "restoring {}: {e} (a copy is in {})",
+ path.display(),
+ self.dir.display()
+ ));
+ }
+ }
+ if let Some(e) = first_err {
+ return Err(e);
+ }
+ let _ = fs::remove_dir_all(&self.dir);
+ Ok(())
+ }
+}
+
+impl Drop for Patches {
+ fn drop(&mut self) {
+ let _ = self.restore();
+ }
+}
+
+fn restore_leftovers(dir: &Path) -> Result<()> {
+ let Ok(entries) = fs::read_dir(dir) else { return Ok(()) };
+ for e in entries.flatten() {
+ let p = e.path();
+ if p.extension().is_some_and(|x| x == "path") {
+ let target = PathBuf::from(fs::read_to_string(&p)?);
+ let orig = p.with_extension("orig");
+ if orig.exists() {
+ fs::copy(&orig, &target).with_context(|| format!("restoring {}", target.display()))?;
+ } else {
+ let _ = fs::remove_file(&target);
+ }
+ crate::ui::warn(format!("restored {} from an interrupted run", target.display()));
+ }
+ }
+ let _ = fs::remove_dir_all(dir);
+ Ok(())
+}
+
+// ------------------------------------------------------------------ blocks inside a function body
+
+fn code_part(line: &str) -> &str {
+ let line = line.split("//").next().unwrap_or(line);
+ line.trim_end()
+}
+
+/// 0-based index of the line whose last code character is the { that opens the function's body.
+/// The function is the header line nearest to hint (1-based) that is_header accepts.
+pub fn body_line(text: &str, hint: u32, is_header: impl Fn(&str) -> bool) -> Option<usize> {
+ let lines: Vec<&str> = text.lines().collect();
+ let header =
+ (0..lines.len()).filter(|&i| is_header(lines[i])).min_by_key(|&i| (i as i64 + 1 - hint as i64).abs())?;
+ for (j, line) in lines.iter().enumerate().skip(header).take(40) {
+ let code = code_part(line);
+ if code.ends_with('{') {
+ return Some(j);
+ }
+ if code.ends_with(';') || (j > header && code.ends_with('}')) {
+ return None;
+ }
+ }
+ None
+}
+
+/// Insert (or replace) the block for id right after the body's opening line, indented like the body.
+pub fn insert_in_body(
+ text: &str,
+ comment: &str,
+ id: &str,
+ body: &str,
+ find: impl Fn(&str) -> Option<usize>,
+) -> Result<String> {
+ let text = strip_in_body(text, comment, id);
+ let Some(at) = find(&text) else {
+ bail!("couldn't find where the function's body starts (its {{ must end a line)")
+ };
+ let nl = if text.contains("\r\n") { "\r\n" } else { "\n" };
+ let lines: Vec<&str> = text.split_inclusive('\n').collect();
+ let indent_of = |l: &str| l.chars().take_while(|c| *c == ' ' || *c == '\t').collect::<String>();
+ let open = indent_of(lines[at]);
+ let next = lines[at + 1..].iter().find(|l| !l.trim().is_empty()).map(|l| indent_of(l)).unwrap_or_default();
+ let indent = if next.len() > open.len() { next } else { format!("{open} ") };
+ let (begin, end) = backend::markers(comment, id);
+ let mut block = format!("{indent}{begin}{nl}");
+ for line in body.lines() {
+ block.push_str(&format!("{indent}{line}{nl}"));
+ }
+ block.push_str(&format!("{indent}{end}{nl}"));
+ let offset: usize = lines[..=at].iter().map(|l| l.len()).sum();
+ let mut head = text[..offset].to_string();
+ if !head.ends_with('\n') {
+ head.push_str(nl);
+ }
+ Ok(format!("{head}{block}{}", &text[offset..]))
+}
+
+/// Remove the block for id; the rest comes back byte for byte.
+pub fn strip_in_body(text: &str, comment: &str, id: &str) -> String {
+ let (begin, end) = backend::markers(comment, id);
+ let Some(b) = text.find(&begin) else { return text.to_string() };
+ let Some(e) = text[b..].find(&end).map(|e| b + e + end.len()) else { return text.to_string() };
+ let start = text[..b].rfind('\n').map(|p| p + 1).unwrap_or(0);
+ let stop = text[e..].find('\n').map(|p| e + p + 1).unwrap_or(text.len());
+ format!("{}{}", &text[..start], &text[stop..])
+}
+
+/// A file next to the original, named so it sorts last and is easy to spot.
+pub fn sibling(file: &Path, name: &str) -> Result<PathBuf> {
+ Ok(file.parent().context("file has no folder")?.join(name))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn body_blocks_come_out_byte_for_byte() {
+ let header = |l: &str| l.contains("func lev(");
+ for original in [
+ "package main\n\nfunc lev(a, b string) int {\n\treturn 1\n}\n",
+ "package main\r\n\r\nfunc lev(a, b string) int { // the distance\r\n\treturn 1\r\n}\r\n",
+ "x\nfunc lev(a string,\n b string) int\n{\n return 1;\n}\n",
+ ] {
+ let find = |t: &str| body_line(t, 3, header);
+ let patched = insert_in_body(original, "//", "main.lev", "if fast() {\n\treturn 2\n}", find).unwrap();
+ assert!(patched.contains("// >>> fast-anything: main.lev >>>"));
+ assert_eq!(
+ insert_in_body(&patched, "//", "main.lev", "if fast() {\n\treturn 2\n}", find).unwrap(),
+ patched
+ );
+ assert_eq!(strip_in_body(&patched, "//", "main.lev"), original);
+ }
+ assert!(body_line("abstract int lev(int a);\n", 1, |l| l.contains("lev(")).is_none());
+ }
+
+ #[test]
+ fn values_compare_like_the_languages_do() {
+ let j = |s: &str| serde_json::from_str::<Value>(s).unwrap();
+ assert!(same(&j("[1, 2.0]"), &j("[1, 2.0000000000001]"), false));
+ assert!(!same(&j("[1]"), &j("[2]"), false));
+ assert!(same(&j("null"), &j("[]"), true) && !same(&j("null"), &j("[]"), false));
+ assert!(same(&j("{\"a\": [1]}"), &j("{\"a\": [1]}"), false));
+ assert!(same(&j("3"), &j("3.0"), false));
+ }
+}
diff --git a/src/node.rs b/src/node.rs
index 5ccd39d..c1841c8 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -508,6 +508,7 @@ mod tests {
enabled: false,
lang: backend::Lang::Node,
owner: None,
+ line: 1,
};
let esm = shim(&port, "./.fast/lib/fa_fuzzy_levenshtein.node", true);
assert!(esm.contains("createRequire(import.meta.url)(\"./.fast/lib/fa_fuzzy_levenshtein.node\").levenshtein"));
diff --git a/src/pipeline.rs b/src/pipeline.rs
index 7e9f229..7906783 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -108,6 +108,7 @@ pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {
enabled,
lang,
owner: hs.owner.clone(),
+ line: hs.line,
};
let helpers: Vec<Hotspot> = hs
.calls
@@ -120,7 +121,7 @@ pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {
ctx.save()?;
Ok(PortOut {
id: hs.id,
- lib_rs: dir.join("src").join(if lang == Lang::Ruby { "port.rs" } else { "lib.rs" }),
+ lib_rs: dir.join("src").join(if lang.c_bridge() { "port.rs" } else { "lib.rs" }),
task_md: dir.join("TASK.md"),
crate_dir: dir,
recorded: rec.kept,
@@ -153,7 +154,7 @@ pub fn verify(root: &Path, id: Option<&str>) -> Result<(String, Verify)> {
if let Some(p) = ctx.state.ports.get_mut(&id) {
p.enabled = false;
}
- ui::warn(format!("{id} was enabled; switched it back to Python until it passes again"));
+ ui::warn(format!("{id} was enabled; switched it back to {} until it passes again", port.lang.label()));
}
if let Some(p) = ctx.state.ports.get_mut(&id) {
p.verify = Some(v.clone());
@@ -233,7 +234,7 @@ pub fn feedback(v: &Verify) -> String {
out.push_str(&format!("- `{}` should give `{}`, the port gave `{}`\n", f.call, f.expected, f.got));
}
}
- out.push_str("\nFix src/lib.rs.\n");
+ out.push_str(if v.lang.c_bridge() { "\nFix src/port.rs.\n" } else { "\nFix src/lib.rs.\n" });
out
}
diff --git a/src/python.rs b/src/python.rs
index 99503a2..834d595 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -489,6 +489,7 @@ mod tests {
enabled: false,
lang: crate::backend::Lang::Python,
owner: None,
+ line: 1,
}
}
diff --git a/src/ruby.rs b/src/ruby.rs
index 11992c3..b415faf 100644
--- a/src/ruby.rs
+++ b/src/ruby.rs
@@ -4,6 +4,7 @@
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};
@@ -130,75 +131,6 @@ pub fn default_json(value: &str) -> Option<String> {
})
}
-fn snake(name: &str) -> String {
- let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
- match s.as_str() {
- "type" | "match" | "fn" | "ref" | "move" | "loop" | "mod" | "use" | "impl" | "self" | "box" | "gen" | "in" => {
- format!("r#{s}")
- }
- _ => s,
- }
-}
-
-pub fn glue_rs(hs: &Hotspot, port: &Port) -> String {
- let args: Vec<String> = hs
- .params
- .iter()
- .enumerate()
- .map(|(i, p)| match p.default.as_deref().and_then(default_json) {
- Some(d) => format!("arg(&args, {i}, Some({d:?}))?"),
- None => format!("arg(&args, {i}, None)?"),
- })
- .collect();
- format!(
- "//! C entry point generated by fast-anything: JSON array of arguments in, {{\"ok\": result}} or\n\
- //! {{\"error\": message}} out. Don't edit this file; the port lives in src/port.rs.\n\n\
- mod port;\n\n\
- use serde_json::{{Value, json}};\n\n\
- fn arg<T: serde::de::DeserializeOwned>(args: &[Value], i: usize, default: Option<&str>) -> Result<T, String> {{\n \
- match args.get(i) {{\n \
- Some(v) => T::deserialize(v).map_err(|e| format!(\"argument {{}}: {{e}}\", i + 1)),\n \
- None => match default {{\n \
- Some(d) => serde_json::from_str(d).map_err(|e| e.to_string()),\n \
- None => Err(format!(\"missing argument {{}}\", i + 1)),\n \
- }},\n \
- }}\n\
- }}\n\n\
- fn call(input: &[u8]) -> Result<Value, String> {{\n \
- let args: Vec<Value> = serde_json::from_slice(input).map_err(|e| e.to_string())?;\n \
- let result = port::{func}({args})?;\n \
- serde_json::to_value(result).map_err(|e| e.to_string())\n\
- }}\n\n\
- /// # Safety\n\
- /// input must point to len readable bytes and out_len to a writable usize.\n\
- #[unsafe(no_mangle)]\n\
- pub unsafe extern \"C\" fn fa_call(input: *const u8, len: usize, out_len: *mut usize) -> *mut u8 {{\n \
- let input = unsafe {{ std::slice::from_raw_parts(input, len) }};\n \
- let reply = match std::panic::catch_unwind(|| call(input)) {{\n \
- Ok(Ok(value)) => json!({{ \"ok\": value }}),\n \
- Ok(Err(message)) => json!({{ \"error\": message }}),\n \
- Err(panic) => {{\n \
- let text = panic.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| panic.downcast_ref::<String>().cloned());\n \
- json!({{ \"error\": format!(\"panic: {{}}\", text.unwrap_or_default()) }})\n \
- }}\n \
- }};\n \
- let bytes = serde_json::to_vec(&reply).unwrap_or_default().into_boxed_slice();\n \
- unsafe {{ *out_len = bytes.len() }};\n \
- Box::into_raw(bytes) as *mut u8\n\
- }}\n\n\
- /// # Safety\n\
- /// ptr and len must come from fa_call.\n\
- #[unsafe(no_mangle)]\n\
- pub unsafe extern \"C\" fn fa_free(ptr: *mut u8, len: usize) {{\n \
- if !ptr.is_null() {{\n \
- drop(unsafe {{ Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr, len)) }});\n \
- }}\n\
- }}\n",
- func = snake(&hs.name),
- args = args.join(", "),
- ) + &format!("\n// {}\n", port.id)
-}
-
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!(
@@ -216,18 +148,6 @@ pub fn port_rs(hs: &Hotspot, port: &Port) -> String {
)
}
-fn cargo_toml(port: &Port) -> String {
- format!(
- "# Rust port of {id}, generated by fast-anything.\n\
- [package]\nname = \"{ext}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\n\
- [lib]\nname = \"{ext}\"\ncrate-type = [\"cdylib\"]\n\n\
- [dependencies]\nserde = {{ version = \"1\", features = [\"derive\"] }}\nserde_json = \"1\"\n\n{profile}",
- id = port.id,
- ext = port.ext,
- profile = backend::RELEASE_PROFILE,
- )
-}
-
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| {
@@ -299,7 +219,7 @@ pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Re
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"), glue_rs(hs, port))?;
+ fs::write(dir.join("src/lib.rs"), crate::native::glue_rs(hs, port, default_json))?;
let body = dir.join("src/port.rs");
if !body.exists() {
fs::write(&body, port_rs(hs, port))?;
diff --git a/src/state.rs b/src/state.rs
index 5ecdc78..2caba0b 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/\nrunner.py\njob-*.json\nprofile.json\nverify.json\n*.jsonl\n*.log\n";
+target/\nlib/\nbin/\nbackup/\nrunner.*\nrecorder.*\nDescribe.java\n*.txt\njob-*.json\nprofile.*\n*.pprof\nverify.json\n*.jsonl\n*.meta.json\n*.log\n";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
@@ -48,6 +48,9 @@ pub struct Port {
pub lang: Lang,
#[serde(default)]
pub owner: Option<String>,
+ /// Where the function started when it was ported (to find it again among overloads).
+ #[serde(default)]
+ pub line: u32,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]