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.1.0

EL4CTEO4ea2b4f0184a
diff --git a/.claude-plugin/icon.png b/.claude-plugin/icon.png
new file mode 100644
index 0000000..9bb699c
Binary files /dev/null and b/.claude-plugin/icon.png differ
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
new file mode 100644
index 0000000..b46118e
--- /dev/null
+++ b/.claude-plugin/marketplace.json
@@ -0,0 +1,14 @@
+{
+ "name": "fast-anything",
+ "owner": {
+ "name": "EL4CTEO"
+ },
+ "plugins": [
+ {
+ "name": "fast-anything",
+ "source": "./",
+ "description": "Port your app's hottest functions to Rust and prove they behave the same."
+ }
+ ],
+ "description": "fast-anything: port your app's hottest functions to Rust and prove they behave the same."
+}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
new file mode 100644
index 0000000..6267b1a
--- /dev/null
+++ b/.claude-plugin/plugin.json
@@ -0,0 +1,21 @@
+{
+ "name": "fast-anything",
+ "version": "0.1.0",
+ "description": "Find the slow 5% of your app, port just that to Rust, and prove it still behaves the same.",
+ "author": {
+ "name": "EL4CTEO"
+ },
+ "homepage": "https://github.com/EL4CTEO/fast-anything",
+ "repository": "https://github.com/EL4CTEO/fast-anything",
+ "license": "MIT",
+ "keywords": [
+ "rust",
+ "python",
+ "nodejs",
+ "typescript",
+ "performance",
+ "pyo3",
+ "napi-rs",
+ "profiling"
+ ]
+}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..bb7541d
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,77 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+jobs:
+ test:
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ python: ["3.10", "3.14"]
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: clippy, rustfmt
+ - uses: actions/setup-python@v7
+ with:
+ python-version: ${{ matrix.python }}
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 24
+ - uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: "3.4"
+ - uses: Swatinem/rust-cache@v2
+ - run: cargo fmt --check
+ - run: cargo clippy --all-targets -- -D warnings
+ - run: cargo test
+ - run: cargo build --release
+ - name: end to end on the demo (reference port instead of an agent)
+ working-directory: examples/fuzzy-dedupe
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- python app.py
+ $fa port
+ cp reference/lib.rs .fast/ports/$(ls .fast/ports)/src/lib.rs
+ $fa verify
+ $fa enable
+ python app.py
+ $fa bench --runs 2
+ $fa report
+ $fa disable
+ git diff --exit-code fuzzy.py
+ - name: end to end, TypeScript
+ working-directory: examples/fuzzy-dedupe-ts
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- node app.ts
+ $fa port
+ cp reference/lib.rs .fast/ports/$(ls .fast/ports)/src/lib.rs
+ $fa verify
+ $fa enable
+ node app.ts
+ $fa bench --runs 2
+ $fa disable
+ git diff --exit-code fuzzy.ts
+ - name: end to end, Ruby
+ working-directory: examples/fuzzy-dedupe-rb
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- ruby app.rb
+ $fa port
+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs
+ $fa verify
+ $fa enable
+ ruby app.rb
+ $fa bench --runs 2
+ $fa disable
+ git diff --exit-code fuzzy.rb
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..dd31e0a
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,92 @@
+name: release
+
+on:
+ push:
+ tags: ["v*"]
+
+permissions:
+ contents: write
+ id-token: write
+
+jobs:
+ build:
+ strategy:
+ matrix:
+ include:
+ - { os: ubuntu-latest, target: x86_64-unknown-linux-gnu, ext: "" }
+ - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu, ext: "" }
+ - { os: macos-latest, target: aarch64-apple-darwin, ext: "" }
+ - { os: macos-13, target: x86_64-apple-darwin, ext: "" }
+ - { os: windows-latest, target: x86_64-pc-windows-msvc, ext: ".exe" }
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.target }}
+ - run: cargo build --release --target ${{ matrix.target }}
+ - name: package
+ run: |
+ name=fast-anything-${{ matrix.target }}
+ mkdir "$name" bin
+ cp target/${{ matrix.target }}/release/fast-anything${{ matrix.ext }} README.md LICENSE "$name/"
+ cp target/${{ matrix.target }}/release/fast-anything${{ matrix.ext }} bin/
+ if [ "${{ matrix.ext }}" = ".exe" ]; then 7z a "$name.zip" "$name" >/dev/null; else tar czf "$name.tar.gz" "$name"; fi
+ - uses: actions/upload-artifact@v7
+ with:
+ name: archive-${{ matrix.target }}
+ path: fast-anything-*.*
+ - uses: actions/upload-artifact@v7
+ with:
+ name: bin-${{ matrix.target }}
+ path: bin/
+
+ github:
+ needs: build
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/download-artifact@v8
+ with:
+ pattern: archive-*
+ merge-multiple: true
+ - name: notes from CHANGELOG.md
+ run: |
+ version="${GITHUB_REF_NAME#v}"
+ awk -v v="## $version" '$0==v{on=1;next} /^## /{on=0} on' CHANGELOG.md > notes.md
+ - uses: softprops/action-gh-release@v3
+ with:
+ body_path: notes.md
+ files: fast-anything-*
+
+ npm:
+ needs: build
+ runs-on: ubuntu-latest
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 24
+ registry-url: https://registry.npmjs.org
+ - uses: actions/download-artifact@v8
+ with:
+ pattern: bin-*
+ path: dist
+ - if: env.NODE_AUTH_TOKEN != ''
+ run: node npm/publish.mjs "${GITHUB_REF_NAME#v}" dist
+
+ crates:
+ needs: build
+ runs-on: ubuntu-latest
+ env:
+ CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@stable
+ - if: env.CARGO_REGISTRY_TOKEN != ''
+ run: cargo publish
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e46214b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+/target
+**/.fast/target/
+**/.fast/lib/
+examples/*/.fast/
diff --git a/.mcp.json b/.mcp.json
new file mode 100644
index 0000000..23f00d2
--- /dev/null
+++ b/.mcp.json
@@ -0,0 +1,10 @@
+{
+ "mcpServers": {
+ "fast-anything": {
+ "command": "fast-anything",
+ "args": [
+ "mcp"
+ ]
+ }
+ }
+}
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..a05f6d4
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,11 @@
+# Changelog
+
+## 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).
+- Ports functions in the entry script too, when its main code is under a main guard.
+- Ports the outermost hot loop, with the helpers it calls, so the app crosses into Rust once instead of per call.
+- Verifies against up to 500 real recorded calls plus derived cases (shrunk inputs answered by the original).
+- `go --agent claude|codex|<cmd>`: the whole loop in one command. `doctor` checks your toolchain.
+- MCP server (`fast-anything mcp`), Claude Code plugin and agent skill.
+- npm (`npm i -g @el4cteo/fast-anything`) and crates.io packages, prebuilt binaries for Windows, macOS and Linux.
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..bcfc58c
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,256 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "clap"
+version = "4.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "fast-anything"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itoa"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..da380eb
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "fast-anything"
+version = "0.1.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"]
+categories = ["command-line-utilities", "development-tools::profiling"]
+exclude = ["examples/*/.fast", ".github", "docs/assets"]
+
+[[bin]]
+name = "fast-anything"
+path = "src/main.rs"
+
+[dependencies]
+anyhow = "1.0.104"
+clap = { version = "4.6.9", features = ["derive"] }
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.154"
+
+[profile.release]
+lto = "fat"
+codegen-units = 1
+strip = true
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0d7f78f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,96 @@
+<p align="center">
+ <img src="https://raw.githubusercontent.com/EL4CTEO/fast-anything/main/docs/assets/wordmark.png" alt="fast-anything" width="520">
+</p>
+
+<p align="center"><b>Don't rewrite it in Rust. Rewrite the 5% that's slow.</b></p>
+
+<p align="center">
+ <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/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>
+</p>
+
+Rewriting a whole app in Rust costs months, minute-long compiles and gigabytes of `target/`. Most of the runtime sits in a few functions anyway.
+
+**fast-anything** finds those functions, has your coding agent port *only them* to Rust, proves the port gives the same results on real recorded calls, and swaps it in. One command, fully reversible.
+
+<p align="center"><img src="https://raw.githubusercontent.com/EL4CTEO/fast-anything/main/docs/assets/demo.gif" alt="fast-anything go --agent claude -- python app.py" width="820"></p>
+
+## Install
+
+```sh
+npm i -g @el4cteo/fast-anything # or: cargo install fast-anything
+```
+
+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
+```
+
+Or step by step:
+
+| command | what it does |
+|---|---|
+| `scan -- <cmd>` | profiles the app, ranks functions by time × how portable they are |
+| `port [id]` | records up to 500 real calls, creates a one-function Rust crate + `TASK.md` |
+| `verify` | release-builds the port and replays every recorded call |
+| `enable` / `disable` | swaps the Rust in or out (one marked block, removed byte for byte) |
+| `bench` | times the whole app, original vs Rust, interleaved runs |
+| `report` | markdown + SVG card for your PR |
+| `doctor` | checks Rust, your runtimes and your agents |
+
+`--agent` takes `claude`, `codex`, or any command that reads a prompt on stdin. Without it, hand `TASK.md` to whatever you use.
+
+## Proof, not vibes
+
+<p align="center"><img src="https://raw.githubusercontent.com/EL4CTEO/fast-anything/main/docs/assets/verify.gif" alt="verify catches a wrong port" width="820"></p>
+
+That port looked right but compared bytes instead of characters. 148 of 500 real calls caught it. On top of the recorded calls, fast-anything derives extra cases by shrinking recorded inputs (empty, tiny, random slices) and lets the original answer them. Nothing is enabled until every case matches: same values (floats within 1e-9), errors where the original errors. `FAST_ANYTHING_DISABLE=1` runs the original any time.
+
+## Results
+
+Real runs on an i5-10500, Windows 11. Reproduce them from [`examples/`](examples).
+
+| app | before | after |
+|---|---|---|
+| Python fuzzy dedupe (700 names) | 4.91s | **42ms, 116×** |
+| TypeScript fuzzy dedupe (2,000 names) | 3.11s | **155ms, 20×** |
+| Ruby fuzzy dedupe (400 names) | 3.13s | **228ms, 14×** |
+
+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×.
+
+## Why not rewrite it all?
+
+- **Compile time**: each port is a one-function crate. Seconds, not minutes.
+- **Cache**: every port shares one `.fast/target`. Delete it whenever you like.
+- **Risk**: your code stays as it is. Rust is opt-in per function, checked against real behavior.
+
+## Agents
+
+- **Claude Code plugin**: `/plugin marketplace add EL4CTEO/fast-anything`, then `/plugin install fast-anything@fast-anything` and `/fast-anything:fast python app.py`
+- **MCP server** (Claude Code, Codex, Cursor…), built into the binary: `claude mcp add fast-anything -- fast-anything mcp`. 8 tools: `fast_scan`, `fast_port`, `fast_verify`, `fast_enable`, `fast_disable`, `fast_bench`, `fast_report`, `fast_status`.
+- **Skill**: [`skills/fast-anything`](skills/fast-anything/SKILL.md) teaches any agent the loop.
+
+## Languages
+
+| language | binding | status |
+|---|---|---|
+| 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 |
+
+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.
+
+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.
+
+## License
+
+MIT
diff --git a/commands/fast.md b/commands/fast.md
new file mode 100644
index 0000000..7f14f0e
--- /dev/null
+++ b/commands/fast.md
@@ -0,0 +1,9 @@
+---
+description: Speed up this app by porting its hottest functions to Rust (fast-anything)
+argument-hint: "[command that runs the app, e.g. python app.py]"
+---
+
+Use the fast-anything skill to speed up this project. The app runs with: $ARGUMENTS
+
+If no command was given, find out how the app is run (README, __main__, pyproject scripts). Only ask if it's truly unclear.
+Report the end-to-end and per-call speedups at the end.
diff --git a/docs/assets/demo.gif b/docs/assets/demo.gif
new file mode 100644
index 0000000..2330537
Binary files /dev/null and b/docs/assets/demo.gif differ
diff --git a/docs/assets/logo-256.png b/docs/assets/logo-256.png
new file mode 100644
index 0000000..9f2334d
Binary files /dev/null and b/docs/assets/logo-256.png differ
diff --git a/docs/assets/logo.png b/docs/assets/logo.png
new file mode 100644
index 0000000..9bb699c
Binary files /dev/null and b/docs/assets/logo.png differ
diff --git a/docs/assets/mark.png b/docs/assets/mark.png
new file mode 100644
index 0000000..28be75e
Binary files /dev/null and b/docs/assets/mark.png differ
diff --git a/docs/assets/social.png b/docs/assets/social.png
new file mode 100644
index 0000000..c015b98
Binary files /dev/null and b/docs/assets/social.png differ
diff --git a/docs/assets/verify.gif b/docs/assets/verify.gif
new file mode 100644
index 0000000..b4b2237
Binary files /dev/null and b/docs/assets/verify.gif differ
diff --git a/docs/assets/wordmark.png b/docs/assets/wordmark.png
new file mode 100644
index 0000000..c85a634
Binary files /dev/null and b/docs/assets/wordmark.png differ
diff --git a/examples/fuzzy-dedupe-rb/app.rb b/examples/fuzzy-dedupe-rb/app.rb
new file mode 100644
index 0000000..2d5e317
--- /dev/null
+++ b/examples/fuzzy-dedupe-rb/app.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+# Find near-duplicate customer names, the slow way.
+# ruby app.rb
+require_relative "fuzzy"
+
+FIRST = %w[Maria Giulia Sofia Luca Marco Matteo José Zoë Łukasz Aiko Chen Olga Ahmed Fatima Liam Emma Noah Ava Mateo Ingrid].freeze
+LAST = %w[Rossi Russo Ferrari Esposito Bianchi García Müller Nowak Tanaka Wang Ivanova Haddad Smith Johnson Brown Silva Kowalski Novák Dubois Larsen].freeze
+
+def make_names(count, seed = 7)
+ rng = Random.new(seed)
+ Array.new(count) do
+ name = "#{FIRST.sample(random: rng)} #{LAST.sample(random: rng)}"
+ if rng.rand < 0.35
+ i = rng.rand(name.length)
+ name = name[0, i] + "aeiourstln"[rng.rand(10)] + name[(i + 1)..]
+ end
+ name
+ end
+end
+
+if __FILE__ == $0
+ names = make_names(400)
+ pairs = Fuzzy.find_duplicates(names)
+ puts "#{names.length} names, #{pairs.length} likely duplicate pairs"
+ pairs.reject { |i, j| names[i] == names[j] }.first(5).each { |i, j| puts " #{names[i]} ~ #{names[j]}" }
+end
diff --git a/examples/fuzzy-dedupe-rb/fuzzy.rb b/examples/fuzzy-dedupe-rb/fuzzy.rb
new file mode 100644
index 0000000..1fa7d5b
--- /dev/null
+++ b/examples/fuzzy-dedupe-rb/fuzzy.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+# Fuzzy string matching helpers.
+module Fuzzy
+ # Edit distance: how many inserts, deletes or substitutions turn a into b.
+ def self.levenshtein(a, b)
+ a, b = b, a if a.length < b.length
+ previous = (0..b.length).to_a
+ a.each_char.with_index(1) do |ca, i|
+ current = [i]
+ b.each_char.with_index(1) do |cb, j|
+ current << [previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (ca == cb ? 0 : 1)].min
+ end
+ previous = current
+ end
+ previous.last
+ end
+
+ def self.normalize(name)
+ name.downcase.split.join(" ")
+ end
+
+ # Index pairs of names within max_distance edits of each other.
+ def self.find_duplicates(names, max_distance = 2)
+ clean = names.map { |n| normalize(n) }
+ pairs = []
+ clean.each_index do |i|
+ ((i + 1)...clean.length).each do |j|
+ pairs << [i, j] if levenshtein(clean[i], clean[j]) <= max_distance
+ end
+ end
+ pairs
+ end
+end
diff --git a/examples/fuzzy-dedupe-rb/reference/port.rs b/examples/fuzzy-dedupe-rb/reference/port.rs
new file mode 100644
index 0000000..2a9d4fe
--- /dev/null
+++ b/examples/fuzzy-dedupe-rb/reference/port.rs
@@ -0,0 +1,75 @@
+//! Reference port of Fuzzy.find_duplicates (with levenshtein and normalize inside it):
+//! what a good agent run produces. CI uses it to test the pipeline without an agent.
+
+/// Ruby's name.downcase.split.join(" "): split only splits on ASCII whitespace.
+fn normalize(name: &str) -> Vec<char> {
+ let lower = name.to_lowercase();
+ let mut out = Vec::with_capacity(lower.len());
+ for word in lower.split(|c: char| matches!(c, ' ' | '\t' | '\n' | '\x0B' | '\x0C' | '\r')).filter(|w| !w.is_empty()) {
+ if !out.is_empty() {
+ out.push(' ');
+ }
+ out.extend(word.chars());
+ }
+ out
+}
+
+pub fn find_duplicates(names: Vec<String>, max_distance: i64) -> Result<Vec<(i64, i64)>, String> {
+ if max_distance < 0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<char>> = names.iter().map(|n| normalize(n)).collect();
+ Ok(pairs(&clean, max_distance as usize).into_iter().map(|(i, j)| (i as i64, j as i64)).collect())
+}
+
+/// Edit distance, one row on the shorter side; stops early once it can't be <= limit.
+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 same order as the nested loops.
+/// Rows are spread over threads round-robin, then merged back into order.
+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() {
+ // the distance is at least the length difference
+ 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-ts/app.ts b/examples/fuzzy-dedupe-ts/app.ts
new file mode 100644
index 0000000..dd81b49
--- /dev/null
+++ b/examples/fuzzy-dedupe-ts/app.ts
@@ -0,0 +1,35 @@
+// Find near-duplicate customer names, the slow way.
+// node app.ts
+import { findDuplicates } from "./fuzzy.ts";
+
+const FIRST = ["Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",
+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"];
+const LAST = ["Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka", "Wang",
+ "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"];
+
+function rng(seed: number) {
+ return () => {
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function makeNames(n: number): string[] {
+ const random = rng(7);
+ const pick = <T,>(xs: T[]) => xs[Math.floor(random() * xs.length)];
+ return Array.from({ length: n }, () => {
+ let name = pick(FIRST) + " " + pick(LAST);
+ if (random() < 0.35) {
+ const i = Math.floor(random() * name.length);
+ name = name.slice(0, i) + pick([..."aeiourstln"]) + name.slice(i + 1);
+ }
+ return name;
+ });
+}
+
+const names = makeNames(2000);
+const pairs = findDuplicates(names);
+console.log(`${names.length} names, ${pairs.length} likely duplicate pairs`);
+for (const [i, j] of pairs.filter(([i, j]) => names[i] !== names[j]).slice(0, 5)) console.log(` ${names[i]} ~ ${names[j]}`);
diff --git a/examples/fuzzy-dedupe-ts/fuzzy.ts b/examples/fuzzy-dedupe-ts/fuzzy.ts
new file mode 100644
index 0000000..fbd5408
--- /dev/null
+++ b/examples/fuzzy-dedupe-ts/fuzzy.ts
@@ -0,0 +1,29 @@
+// Fuzzy string matching helpers.
+
+/** Edit distance: how many inserts, deletes or substitutions turn a into b. */
+export function levenshtein(a: string, b: string): number {
+ if (a.length < b.length) [a, b] = [b, a];
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
+ for (let i = 1; i <= a.length; i++) {
+ const current = [i];
+ for (let j = 1; j <= b.length; j++) {
+ current.push(Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)));
+ }
+ previous = current;
+ }
+ return previous[b.length];
+}
+
+export function normalize(name: string): string {
+ return name.toLowerCase().split(/\s+/).filter(Boolean).join(" ");
+}
+
+/** Index pairs of names within maxDistance edits of each other. */
+export function findDuplicates(names: string[], maxDistance: number = 2): [number, number][] {
+ const clean = names.map(normalize);
+ const pairs: [number, number][] = [];
+ for (let i = 0; i < clean.length; i++)
+ for (let j = i + 1; j < clean.length; j++)
+ if (levenshtein(clean[i], clean[j]) <= maxDistance) pairs.push([i, j]);
+ return pairs;
+}
diff --git a/examples/fuzzy-dedupe-ts/package.json b/examples/fuzzy-dedupe-ts/package.json
new file mode 100644
index 0000000..bf56c69
--- /dev/null
+++ b/examples/fuzzy-dedupe-ts/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "fuzzy-dedupe-ts",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "start": "node app.ts"
+ }
+}
diff --git a/examples/fuzzy-dedupe-ts/reference/lib.rs b/examples/fuzzy-dedupe-ts/reference/lib.rs
new file mode 100644
index 0000000..7df0350
--- /dev/null
+++ b/examples/fuzzy-dedupe-ts/reference/lib.rs
@@ -0,0 +1,76 @@
+//! 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.
+
+use napi::bindgen_prelude::*;
+use napi_derive::napi;
+
+/// JavaScript's name.toLowerCase().split(/\s+/).filter(Boolean).join(" "), as UTF-16 code units
+/// (what JavaScript compares).
+fn normalize(name: &str) -> Vec<u16> {
+ let lower = name.to_lowercase();
+ let words: Vec<&str> = lower.split(|c: char| c.is_whitespace() || c == '\u{feff}').filter(|w| !w.is_empty()).collect();
+ words.join(" ").encode_utf16().collect()
+}
+
+#[napi(js_name = "findDuplicates", catch_unwind)]
+pub fn find_duplicates(names: Vec<String>, max_distance: Option<f64>) -> Result<Vec<Vec<f64>>> {
+ let max = max_distance.unwrap_or(2.0);
+ if max < 0.0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<u16>> = names.iter().map(|n| normalize(n)).collect();
+ let found = pairs(&clean, max.floor() as usize);
+ Ok(found.into_iter().map(|(i, j)| vec![i as f64, j as f64]).collect())
+}
+
+/// Edit distance, one row on the shorter side; stops early once it can't be <= limit.
+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 same order as the nested loops.
+/// Rows are spread over threads round-robin, then merged back into order.
+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() {
+ // the distance is at least the length difference
+ 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/app.py b/examples/fuzzy-dedupe/app.py
new file mode 100644
index 0000000..31f421e
--- /dev/null
+++ b/examples/fuzzy-dedupe/app.py
@@ -0,0 +1,38 @@
+"""Find near-duplicate customer names, the slow way.
+
+ python app.py
+"""
+
+import random
+
+from fuzzy import find_duplicates
+
+FIRST = ["Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",
+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"]
+LAST = ["Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka", "Wang",
+ "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"]
+
+
+def make_names(n, seed=7):
+ rng = random.Random(seed)
+ names = []
+ for _ in range(n):
+ name = f"{rng.choice(FIRST)} {rng.choice(LAST)}"
+ if rng.random() < 0.35:
+ i = rng.randrange(len(name))
+ name = name[:i] + rng.choice("aeiourstln") + name[i + 1:]
+ names.append(name)
+ return names
+
+
+def main():
+ names = make_names(700)
+ pairs = find_duplicates(names)
+ print(f"{len(names)} names, {len(pairs)} likely duplicate pairs")
+ typos = [(i, j) for i, j in pairs if names[i] != names[j]]
+ for i, j in typos[:5]:
+ print(f" {names[i]!r} ~ {names[j]!r}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/fuzzy-dedupe/fuzzy.py b/examples/fuzzy-dedupe/fuzzy.py
new file mode 100644
index 0000000..d821e4e
--- /dev/null
+++ b/examples/fuzzy-dedupe/fuzzy.py
@@ -0,0 +1,29 @@
+"""Fuzzy string matching helpers."""
+
+
+def levenshtein(a: str, b: str) -> int:
+ """Edit distance: how many inserts, deletes or substitutions turn a into b."""
+ if len(a) < len(b):
+ a, b = b, a
+ previous = list(range(len(b) + 1))
+ for i, ca in enumerate(a, 1):
+ current = [i]
+ for j, cb in enumerate(b, 1):
+ current.append(min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (ca != cb)))
+ previous = current
+ return previous[-1]
+
+
+def normalize(name: str) -> str:
+ return " ".join(name.lower().split())
+
+
+def find_duplicates(names: list[str], max_distance: int = 2) -> list[tuple[int, int]]:
+ """Index pairs of names within max_distance edits of each other."""
+ clean = [normalize(n) for n in names]
+ pairs = []
+ for i in range(len(clean)):
+ for j in range(i + 1, len(clean)):
+ if levenshtein(clean[i], clean[j]) <= max_distance:
+ pairs.append((i, j))
+ return pairs
diff --git a/examples/fuzzy-dedupe/reference/lib.rs b/examples/fuzzy-dedupe/reference/lib.rs
new file mode 100644
index 0000000..cbe3d36
--- /dev/null
+++ b/examples/fuzzy-dedupe/reference/lib.rs
@@ -0,0 +1,86 @@
+//! Reference port of fuzzy.find_duplicates (with levenshtein and normalize inside it):
+//! what a good agent run produces. CI uses it to test the pipeline without an agent.
+
+use pyo3::prelude::*;
+
+/// Python's " ".join(name.lower().split()), as code points.
+fn normalize(name: &str) -> Vec<char> {
+ let lower = name.to_lowercase();
+ let mut out = Vec::with_capacity(lower.len());
+ for (k, word) in lower.split_whitespace().enumerate() {
+ if k > 0 {
+ out.push(' ');
+ }
+ out.extend(word.chars());
+ }
+ out
+}
+
+#[pyfunction]
+#[pyo3(signature = (names, max_distance = 2))]
+fn find_duplicates(py: Python<'_>, names: Vec<String>, max_distance: i64) -> PyResult<Vec<(i64, i64)>> {
+ if max_distance < 0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<char>> = names.iter().map(|n| normalize(n)).collect();
+ let found = py.detach(|| pairs(&clean, max_distance as usize));
+ Ok(found.into_iter().map(|(i, j)| (i as i64, j as i64)).collect())
+}
+
+/// Edit distance, one row on the shorter side; stops early once it can't be <= limit.
+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 same order as the nested loops.
+/// Rows are spread over threads round-robin, then merged back into order.
+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() {
+ // the distance is at least the length difference
+ 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
+}
+
+#[pymodule]
+fn fa_fuzzy_find_duplicates(m: &Bound<'_, PyModule>) -> PyResult<()> {
+ m.add_function(wrap_pyfunction!(find_duplicates, m)?)?;
+ Ok(())
+}
diff --git a/npm/fast-anything/bin/fast-anything.js b/npm/fast-anything/bin/fast-anything.js
new file mode 100644
index 0000000..06f1e83
--- /dev/null
+++ b/npm/fast-anything/bin/fast-anything.js
@@ -0,0 +1,23 @@
+#!/usr/bin/env node
+// Runs the prebuilt fast-anything binary for this platform (installed as an optional dependency).
+"use strict";
+const { spawnSync } = require("node:child_process");
+
+const pkg = `@el4cteo/fast-anything-${process.platform}-${process.arch}`;
+const exe = process.platform === "win32" ? "fast-anything.exe" : "fast-anything";
+let bin;
+try {
+ bin = require.resolve(`${pkg}/bin/${exe}`);
+} catch {
+ console.error(
+ `fast-anything: no prebuilt binary for ${process.platform}-${process.arch} (${pkg} isn't installed).\n` +
+ "Reinstall without --omit=optional, or build it: cargo install fast-anything",
+ );
+ process.exit(1);
+}
+const run = spawnSync(bin, process.argv.slice(2), { stdio: "inherit" });
+if (run.error) {
+ console.error(`fast-anything: ${run.error.message}`);
+ process.exit(1);
+}
+process.exit(run.status ?? 1);
diff --git a/npm/fast-anything/package.json b/npm/fast-anything/package.json
new file mode 100644
index 0000000..fa5ea19
--- /dev/null
+++ b/npm/fast-anything/package.json
@@ -0,0 +1,54 @@
+{
+ "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.",
+ "keywords": [
+ "rust",
+ "python",
+ "nodejs",
+ "typescript",
+ "ruby",
+ "performance",
+ "optimization",
+ "profiler",
+ "profiling",
+ "pyo3",
+ "napi-rs",
+ "ffi",
+ "speedup",
+ "rewrite-it-in-rust",
+ "ai-agents",
+ "claude-code",
+ "mcp",
+ "codex",
+ "cli"
+ ],
+ "homepage": "https://github.com/EL4CTEO/fast-anything#readme",
+ "bugs": "https://github.com/EL4CTEO/fast-anything/issues",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/EL4CTEO/fast-anything.git"
+ },
+ "license": "MIT",
+ "bin": {
+ "fast-anything": "bin/fast-anything.js"
+ },
+ "files": [
+ "bin",
+ "README.md",
+ "LICENSE"
+ ],
+ "engines": {
+ "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"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/npm/publish.mjs b/npm/publish.mjs
new file mode 100644
index 0000000..613c578
--- /dev/null
+++ b/npm/publish.mjs
@@ -0,0 +1,63 @@
+// Publishes the npm packages from release binaries:
+// node npm/publish.mjs <version> <dir with bin-<rust target>/fast-anything[.exe]> [--dry-run]
+// One package per platform (@el4cteo/fast-anything-<os>-<cpu>) plus the @el4cteo/fast-anything launcher.
+import { execFileSync } from "node:child_process";
+import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const [version, dist, flag] = process.argv.slice(2);
+if (!version || !dist) throw new Error("usage: node npm/publish.mjs <version> <dist> [--dry-run]");
+const dry = flag === "--dry-run";
+const here = path.dirname(fileURLToPath(import.meta.url));
+const root = path.resolve(here, "..");
+const out = path.join(root, "target", "npm");
+rmSync(out, { recursive: true, force: true });
+
+const TARGETS = {
+ "x86_64-pc-windows-msvc": ["win32", "x64"],
+ "x86_64-unknown-linux-gnu": ["linux", "x64"],
+ "aarch64-unknown-linux-gnu": ["linux", "arm64"],
+ "aarch64-apple-darwin": ["darwin", "arm64"],
+ "x86_64-apple-darwin": ["darwin", "x64"],
+};
+const main = JSON.parse(readFileSync(path.join(here, "fast-anything", "package.json"), "utf8"));
+const publish = (dir) => {
+ const provenance = process.env.GITHUB_ACTIONS ? ["--provenance"] : [];
+ const args = ["publish", "--access", "public", ...(dry ? ["--dry-run"] : provenance)];
+ execFileSync("npm", args, { cwd: dir, stdio: "inherit", shell: process.platform === "win32" });
+};
+
+for (const [target, [os, cpu]] of Object.entries(TARGETS)) {
+ const exe = os === "win32" ? "fast-anything.exe" : "fast-anything";
+ const src = path.join(dist, `bin-${target}`, exe);
+ if (!existsSync(src)) throw new Error(`missing ${src}`);
+ const name = `@el4cteo/fast-anything-${os}-${cpu}`;
+ const dir = path.join(out, `fast-anything-${os}-${cpu}`);
+ mkdirSync(path.join(dir, "bin"), { recursive: true });
+ copyFileSync(src, path.join(dir, "bin", exe));
+ chmodSync(path.join(dir, "bin", exe), 0o755);
+ const pkg = {
+ name,
+ version,
+ description: `The ${os}-${cpu} binary for fast-anything.`,
+ repository: main.repository,
+ license: "MIT",
+ os: [os],
+ cpu: [cpu],
+ ...(os === "linux" ? { libc: ["glibc"] } : {}),
+ files: ["bin"],
+ };
+ writeFileSync(path.join(dir, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
+ publish(dir);
+}
+
+const dir = path.join(out, "fast-anything");
+mkdirSync(path.join(dir, "bin"), { recursive: true });
+copyFileSync(path.join(here, "fast-anything", "bin", "fast-anything.js"), path.join(dir, "bin", "fast-anything.js"));
+copyFileSync(path.join(root, "README.md"), path.join(dir, "README.md"));
+copyFileSync(path.join(root, "LICENSE"), path.join(dir, "LICENSE"));
+main.version = version;
+for (const dep of Object.keys(main.optionalDependencies)) main.optionalDependencies[dep] = version;
+writeFileSync(path.join(dir, "package.json"), JSON.stringify(main, null, 2) + "\n");
+publish(dir);
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..c775577
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1,2 @@
+max_width = 120
+use_small_heuristics = "Max"
diff --git a/scripts/demo_gifs.py b/scripts/demo_gifs.py
new file mode 100644
index 0000000..4b35c34
--- /dev/null
+++ b/scripts/demo_gifs.py
@@ -0,0 +1,162 @@
+"""Renders the README demo GIFs from transcripts of real fast-anything runs.
+
+ python scripts/demo_gifs.py (needs Pillow; Windows fonts by default, set FA_FONT/FA_SYMBOL_FONT elsewhere)
+"""
+
+import os
+import re
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+OUT = Path(__file__).resolve().parent.parent / "docs" / "assets"
+FONT = os.environ.get("FA_FONT", "C:/Windows/Fonts/consola.ttf")
+BOLD = os.environ.get("FA_FONT_BOLD", "C:/Windows/Fonts/consolab.ttf")
+SYMBOL = os.environ.get("FA_SYMBOL_FONT", "C:/Windows/Fonts/seguisym.ttf")
+SIZE, LINE, PAD, BAR = 17, 24, 22, 34
+COLORS = {
+ "": (201, 209, 217), "o": (255, 135, 0), "g": (63, 185, 80), "r": (248, 81, 73),
+ "d": (125, 133, 144), "b": (240, 246, 252), "y": (210, 153, 34), "p": (63, 185, 80),
+}
+BG, CHROME = (13, 17, 23), (22, 27, 34)
+SYMBOLS = set("⚡▸✓✗→·●○↳")
+BLOCKS = {"█": 1.0, "▉": 7 / 8, "▊": 6 / 8, "▋": 5 / 8, "▌": 4 / 8, "▍": 3 / 8, "▎": 2 / 8, "▏": 1 / 8}
+
+font = ImageFont.truetype(FONT, SIZE)
+bold = ImageFont.truetype(BOLD, SIZE)
+symbol = ImageFont.truetype(SYMBOL, SIZE + 1)
+CELL = font.getlength("M")
+
+
+def spans(markup):
+ """'[o]orange[/] plain' -> [(color, text), ...]"""
+ out, color = [], ""
+ for part in re.split(r"(\[[a-z]?\]|\[/\])", markup):
+ if re.fullmatch(r"\[[a-z]?\]", part):
+ color = part[1:-1]
+ elif part == "[/]":
+ color = ""
+ elif part:
+ out.append((color, part))
+ return out
+
+
+def render(lines, width, height, cursor=False):
+ img = Image.new("RGB", (width, height), BG)
+ d = ImageDraw.Draw(img)
+ d.rectangle([0, 0, width, BAR], fill=CHROME)
+ for i, c in enumerate([(255, 95, 86), (255, 189, 46), (39, 201, 63)]):
+ d.ellipse([16 + i * 22, 11, 28 + i * 22, 23], fill=c)
+ d.text((width / 2, BAR / 2), "fast-anything", font=font, fill=COLORS["d"], anchor="mm")
+ y = BAR + PAD - 4
+ last_x = PAD
+ for line in lines:
+ x = PAD
+ for color, text in spans(line):
+ for ch in text:
+ fill = COLORS[color]
+ if ch in BLOCKS:
+ d.rectangle([x, y + 3, x + CELL * BLOCKS[ch] - 1, y + LINE - 5], fill=fill)
+ elif ch in SYMBOLS:
+ d.text((x + CELL / 2, y + LINE / 2 - 2), ch, font=symbol, fill=fill, anchor="mm")
+ else:
+ d.text((x, y + 2), ch, font=bold if color in ("b", "o") else font, fill=fill)
+ x += CELL
+ last_x = x
+ y += LINE
+ if cursor:
+ d.rectangle([last_x + 2, y - LINE + 4, last_x + CELL - 1, y - 4], fill=COLORS[""])
+ return img
+
+
+def make(name, script, width, rows):
+ """script: list of ("type", text) | ("out", line, ms) | ("spin", label, seconds) | ("wait", ms) | ("clear",)"""
+ height = BAR + PAD * 2 + rows * LINE
+ frames, durations, lines = [], [], []
+
+ def snap(ms, cursor=False):
+ frames.append(render(lines[-rows:], width, height, cursor))
+ durations.append(ms)
+
+ for step in script:
+ kind = step[0]
+ if kind == "type":
+ lines.append("[p]$[/] ")
+ text = step[1]
+ for i in range(0, len(text), 3):
+ lines[-1] = "[p]$[/] [b]" + text[: i + 3] + "[/]"
+ snap(45, cursor=True)
+ snap(450, cursor=True)
+ elif kind == "out":
+ lines.append(step[1])
+ snap(step[2] if len(step) > 2 else 90)
+ elif kind == "spin":
+ lines.append("")
+ for i in range(int(step[2] * 8)):
+ lines[-1] = "[o]" + "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"[i % 10] + "[/] " + step[1]
+ snap(110)
+ lines[-1] = "[o]▸[/] " + step[1]
+ snap(60)
+ elif kind == "wait":
+ snap(step[1])
+ elif kind == "clear":
+ lines.clear()
+
+ palette = frames[-1].convert("P", palette=Image.ADAPTIVE, colors=64)
+ frames = [f.quantize(palette=palette, dither=Image.Dither.NONE) for f in frames]
+ frames[0].save(OUT / name, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True, disposal=1)
+ print(name, len(frames), "frames,", (OUT / name).stat().st_size // 1024, "KB")
+
+
+SYMBOL_SPIN = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
+SYMBOLS.update(SYMBOL_SPIN)
+
+GO = [
+ ("type", "fast-anything go --agent claude -- python app.py"),
+ ("out", "[o]⚡ fast-anything[/] [d]v0.1.0[/]"),
+ ("spin", "profiling [b]python app.py[/]", 1.2),
+ ("out", "[g]✓[/] [b]python app.py[/] ran in 21.73s [d](under the profiler)[/]"),
+ ("out", ""),
+ ("out", "[d] # function time calls verdict[/]"),
+ ("out", " 1 fuzzy.find_duplicates [o]█████████[/] 99.9% 1 [g]✓ port it[/]", 160),
+ ("out", "[d] 2 fuzzy.levenshtein █████████ 99.6% 244,650 ↳ ported inside it[/]"),
+ ("out", "[d] 3 fuzzy.normalize 0.0% 700 ↳ ported inside it[/]"),
+ ("out", "[d] 4 app.py:main █████████ 100.0% 1 ✗ lives in the entry script[/]"),
+ ("out", ""),
+ ("spin", "recording real calls to [b]fuzzy.find_duplicates[/]", 0.8),
+ ("spin", "[b]claude[/] is writing the Rust port [d](attempt 1/3)[/]", 2.0),
+ ("spin", "building [b]fa_fuzzy_find_duplicates[/] [d](release)[/]", 0.8),
+ ("spin", "replaying recorded + derived calls against the Rust port", 0.6),
+ ("out", "[g]✓[/] 26/26 calls give the same result [d](1 recorded + 25 derived)[/]", 300),
+ ("out", "[g]✓[/] [b]fuzzy.find_duplicates[/] now runs in Rust"),
+ ("spin", "timing [b]python app.py[/] [d](5 runs each, interleaved)[/]", 1.0),
+ ("out", ""),
+ ("out", " Python [d]████████████████████████[/] 5.05s", 200),
+ ("out", " Rust [o]▎[/] 49ms", 200),
+ ("out", ""),
+ ("out", "[g]✓[/] [b]python app.py[/] is [o]103× faster[/] end to end", 4500),
+]
+
+VERIFY = [
+ ("type", "fast-anything verify"),
+ ("spin", "building [b]fa_fuzzy_levenshtein[/] [d](release)[/]", 0.6),
+ ("spin", "replaying 500 recorded calls against the Rust port", 0.6),
+ ("out", "[r]✗[/] 148/500 recorded calls don't match", 250),
+ ("out", " levenshtein('neah larsen', 'josé smita')"),
+ ("out", " expected [g]10[/]"),
+ ("out", " got [r]11[/]", 250),
+ ("out", " levenshtein('fatima haddad', 'łukasz kowalski')"),
+ ("out", " expected [g]13[/]"),
+ ("out", " got [r]14[/]", 2200),
+ ("out", ""),
+ ("out", "[d]# the port compared bytes, Python compares characters. Fixed:[/]", 1500),
+ ("type", "fast-anything verify"),
+ ("spin", "building [b]fa_fuzzy_levenshtein[/] [d](release)[/]", 0.6),
+ ("spin", "replaying 500 recorded calls against the Rust port", 0.6),
+ ("out", "[g]✓[/] 500/500 recorded calls give the same result", 300),
+ ("out", "[g]✓[/] [b]fuzzy.levenshtein[/] per call: 18.9µs in Python, 450ns in Rust: [o]42× faster[/]", 4000),
+]
+
+if __name__ == "__main__":
+ make("demo.gif", GO, 920, 22)
+ make("verify.gif", VERIFY, 920, 17)
diff --git a/scripts/logo.py b/scripts/logo.py
new file mode 100644
index 0000000..76e18af
--- /dev/null
+++ b/scripts/logo.py
@@ -0,0 +1,166 @@
+"""Renders the fast-anything logo, wordmark and social card (Pillow, 4x supersampled).
+
+The mark is a profiler flame graph that is also a flame: the cool blue base is your
+original code, the hot path's stack is the part fast-anything forged into Rust.
+
+ python scripts/logo.py
+"""
+
+import os
+from pathlib import Path
+
+from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont
+
+OUT = Path(__file__).resolve().parent.parent / "docs" / "assets"
+SS = 4 # supersampling
+
+# (left, right, kind) per row, bottom to top, on a 1024 grid. kind: cool | hot
+ROWS = [
+ [(170, 854, "cool")],
+ [(170, 686, "cool"), (700, 854, "cool")],
+ [(214, 676, "cool"), (714, 834, "cool")],
+ [(262, 662, "hot")],
+ [(296, 618, "hot")],
+ [(332, 580, "hot")],
+ [(372, 530, "hot")],
+ [(404, 478, "hot")],
+]
+BAR_H, GAP, BASE_Y = 78, 12, 846
+
+
+def lerp(a, b, t):
+ return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(len(a)))
+
+
+def vertical_gradient(size, stops):
+ w, h = size
+ img = Image.new("RGBA", size)
+ px = img.load()
+ for y in range(h):
+ t = y / max(1, h - 1)
+ for i in range(len(stops) - 1):
+ (t0, c0), (t1, c1) = stops[i], stops[i + 1]
+ if t0 <= t <= t1:
+ c = lerp(c0, c1, (t - t0) / max(1e-9, t1 - t0))
+ break
+ for x in range(w):
+ px[x, y] = c
+ return img
+
+
+def rounded_mask(size, box, radius):
+ m = Image.new("L", size, 0)
+ ImageDraw.Draw(m).rounded_rectangle(box, radius=radius, fill=255)
+ return m
+
+
+def mark(size=1024, background=True):
+ S = size * SS
+ k = S / 1024
+ canvas = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+
+ if background:
+ bg = vertical_gradient((S, S), [(0, (24, 29, 38, 255)), (1, (8, 10, 14, 255))])
+ glow = Image.new("L", (S, S), 0)
+ ImageDraw.Draw(glow).ellipse([S * 0.18, S * 0.42, S * 0.82, S * 1.02], fill=150)
+ glow = glow.filter(ImageFilter.GaussianBlur(S * 0.09))
+ warm = Image.new("RGBA", (S, S), (255, 110, 20, 255))
+ bg = Image.composite(Image.blend(bg, warm, 0.22), bg, glow)
+ mask = rounded_mask((S, S), [0, 0, S - 1, S - 1], int(S * 0.22))
+ canvas.paste(bg, (0, 0), mask)
+ rim = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+ ImageDraw.Draw(rim).rounded_rectangle([2 * k, 2 * k, S - 2 * k, S - 2 * k], radius=int(S * 0.22), outline=(255, 255, 255, 28), width=int(3 * k))
+ canvas = Image.alpha_composite(canvas, rim)
+
+ hot_layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+ cool_layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+ hot_top = BASE_Y - (len(ROWS) - 1) * (BAR_H + GAP) - BAR_H
+ hot_bottom = BASE_Y - 3 * (BAR_H + GAP)
+ hot_fill = vertical_gradient((S, S), [
+ (0.0, (255, 246, 196, 255)), (hot_top / 1024, (255, 236, 150, 255)),
+ ((hot_top + hot_bottom) / 2048, (255, 168, 40, 255)), (hot_bottom / 1024, (247, 90, 10, 255)), (1.0, (200, 50, 0, 255)),
+ ])
+ cool_fill = vertical_gradient((S, S), [(0.0, (120, 180, 255, 255)), (0.62, (70, 130, 240, 255)), (1.0, (28, 70, 170, 255))])
+
+ hot_mask = Image.new("L", (S, S), 0)
+ cool_mask = Image.new("L", (S, S), 0)
+ shine = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+ ds = ImageDraw.Draw(shine)
+ for r, row in enumerate(ROWS):
+ y1 = BASE_Y - r * (BAR_H + GAP)
+ y0 = y1 - BAR_H
+ for x0, x1, kind in row:
+ box = [x0 * k, y0 * k, x1 * k, y1 * k]
+ target = hot_mask if kind == "hot" else cool_mask
+ ImageDraw.Draw(target).rounded_rectangle(box, radius=int(16 * k), fill=255)
+ ds.rounded_rectangle([box[0] + 10 * k, box[1] + 7 * k, box[2] - 10 * k, box[1] + 15 * k], radius=int(4 * k), fill=(255, 255, 255, 70 if kind == "hot" else 45))
+
+ # glow behind the hot stack
+ halo = hot_mask.filter(ImageFilter.GaussianBlur(38 * k))
+ halo_rgba = Image.new("RGBA", (S, S), (255, 120, 20, 0))
+ halo_rgba.putalpha(halo.point(lambda v: int(v * 0.9)))
+ canvas = Image.alpha_composite(canvas, halo_rgba)
+ cool_halo = cool_mask.filter(ImageFilter.GaussianBlur(30 * k))
+ cool_rgba = Image.new("RGBA", (S, S), (40, 110, 255, 0))
+ cool_rgba.putalpha(cool_halo.point(lambda v: int(v * 0.45)))
+ canvas = Image.alpha_composite(canvas, cool_rgba)
+
+ hot_layer.paste(hot_fill, (0, 0), hot_mask)
+ cool_layer.paste(cool_fill, (0, 0), cool_mask)
+ canvas = Image.alpha_composite(canvas, cool_layer)
+ canvas = Image.alpha_composite(canvas, hot_layer)
+ shine_mask = ImageChops.add(hot_mask, cool_mask)
+ shine_clip = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+ shine_clip.paste(shine, (0, 0), shine_mask)
+ canvas = Image.alpha_composite(canvas, shine_clip)
+
+ # sparks rising off the tip
+ sparks = Image.new("RGBA", (S, S), (0, 0, 0, 0))
+ dsp = ImageDraw.Draw(sparks)
+ for (x, y, r, a) in [(520, 150, 9, 230), (472, 112, 6, 190), (560, 104, 5, 150), (498, 70, 4, 120)]:
+ dsp.ellipse([(x - r) * k, (y - r) * k, (x + r) * k, (y + r) * k], fill=(255, 214, 120, a))
+ canvas = Image.alpha_composite(canvas, sparks.filter(ImageFilter.GaussianBlur(1.5 * k)))
+ canvas = Image.alpha_composite(canvas, sparks)
+ return canvas.resize((size, size), Image.LANCZOS)
+
+
+def font(names, size):
+ for n in names:
+ p = Path("C:/Windows/Fonts") / n
+ if p.exists():
+ return ImageFont.truetype(str(p), size)
+ return ImageFont.load_default(size)
+
+
+def wordmark(width, height, logo_size, title_size, tagline=None, bg=True):
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ if bg:
+ img = vertical_gradient((width, height), [(0, (17, 21, 28, 255)), (1, (8, 10, 14, 255))])
+ logo = mark(logo_size)
+ title = font(["segoeuib.ttf", "seguisb.ttf", "arialbd.ttf"], title_size)
+ small = font(["segoeui.ttf", "arial.ttf"], int(title_size * 0.36))
+ d = ImageDraw.Draw(img)
+ w_fast = d.textlength("fast", font=title)
+ w_any = d.textlength("-anything", font=title)
+ text_w = w_fast + w_any
+ total = logo_size + title_size * 0.45 + text_w
+ x = (width - total) / 2
+ y = (height - logo_size) / 2 - (title_size * 0.32 if tagline else 0)
+ img.alpha_composite(logo, (int(x), int(y)))
+ tx = x + logo_size + title_size * 0.45
+ ty = y + logo_size / 2
+ d.text((tx, ty), "fast", font=title, fill=(240, 246, 252), anchor="lm")
+ d.text((tx + w_fast, ty), "-anything", font=title, fill=(255, 128, 32), anchor="lm")
+ if tagline:
+ d.text((width / 2, y + logo_size + title_size * 0.62), tagline, font=small, fill=(139, 148, 158), anchor="mm")
+ return img
+
+
+if __name__ == "__main__":
+ OUT.mkdir(parents=True, exist_ok=True)
+ mark(1024).save(OUT / "logo.png")
+ mark(256).save(OUT / "logo-256.png")
+ mark(1024, background=False).resize((512, 512), Image.LANCZOS).save(OUT / "mark.png")
+ wordmark(1600, 400, 260, 150, bg=False).save(OUT / "wordmark.png")
+ wordmark(1280, 640, 250, 128, tagline="Don't rewrite it in Rust. Rewrite the 5% that's slow.").convert("RGB").save(OUT / "social.png")
+ print("ok")
diff --git a/skills/fast-anything/SKILL.md b/skills/fast-anything/SKILL.md
new file mode 100644
index 0000000..6bae65f
--- /dev/null
+++ b/skills/fast-anything/SKILL.md
@@ -0,0 +1,33 @@
+---
+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".
+---
+
+# fast-anything
+
+The `fast-anything` CLI measures, records, builds, checks and swaps. You write the Rust.
+(The same steps are MCP tools: `fast_scan`, `fast_port`, `fast_verify`, `fast_enable`, `fast_bench`, `fast_report`.)
+
+## Loop
+
+1. **Scan**: `fast-anything scan -- python app.py`, using the command the user runs their app with
+ (a representative workload, not the test suite). Pick the top function marked "port it".
+ 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):
+ - 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.
+4. **Verify**: `fast-anything verify <id>` builds in release mode and replays every recorded call.
+ On mismatch, read the failing call, fix, verify again. Never edit the recordings.
+5. **Enable**: `fast-anything enable <id>`, then `fast-anything bench` and `fast-anything report`.
+6. Tell the user the end-to-end speedup, the per-call speedup, and how to undo
+ (`fast-anything disable <id>`, or `FAST_ANYTHING_DISABLE=1` for a single run).
+
+## Don't
+
+- Don't edit the original Python function: the block appended to its module does the swap.
+- Don't enable a port that hasn't passed verify.
+- If a function shows ✗ (I/O, randomness, globals, lives in the entry script), say why it can't be ported yet.
+ Suggest moving pure logic into its own module when that's the blocker.
diff --git a/src/agent.rs b/src/agent.rs
new file mode 100644
index 0000000..cfbd824
--- /dev/null
+++ b/src/agent.rs
@@ -0,0 +1,77 @@
+//! Hands TASK.md to a coding agent CLI and lets it edit the crate.
+
+use anyhow::{Context, Result, ensure};
+use std::fs::{self, File};
+use std::io::{ErrorKind, Write};
+use std::path::Path;
+use std::process::{Child, Command, Stdio};
+
+/// Presets for agents we know; anything else is run as given, with the prompt on stdin.
+pub fn argv(spec: &str) -> Vec<String> {
+ let preset: &[&str] = match spec {
+ "claude" => &[
+ "claude",
+ "-p",
+ "--permission-mode",
+ "acceptEdits",
+ "--allowedTools",
+ "Read Edit Write Glob Grep Bash(cargo check:*) Bash(cargo build:*) Bash(cargo test:*) Bash(cargo fmt:*)",
+ ],
+ "codex" => &["codex", "exec", "--full-auto", "-"],
+ _ => &[],
+ };
+ if preset.is_empty() {
+ spec.split_whitespace().map(String::from).collect()
+ } else {
+ preset.iter().map(|s| s.to_string()).collect()
+ }
+}
+
+fn spawn(argv: &[String], dir: &Path, log: &File) -> std::io::Result<Child> {
+ Command::new(&argv[0])
+ .args(&argv[1..])
+ .current_dir(dir)
+ .env_remove("CLAUDECODE")
+ .stdin(Stdio::piped())
+ .stdout(log.try_clone()?)
+ .stderr(log.try_clone()?)
+ .spawn()
+}
+
+pub fn run(spec: &str, dir: &Path, prompt: &str, log_path: &Path) -> Result<()> {
+ let argv = argv(spec);
+ ensure!(!argv.is_empty(), "empty --agent");
+ let log = File::create(log_path)?;
+ let mut child = match spawn(&argv, dir, &log) {
+ // npm-installed agents are .cmd shims on Windows; let cmd.exe find them.
+ Err(e) if e.kind() == ErrorKind::NotFound && cfg!(windows) => {
+ let mut wrapped = vec!["cmd".to_string(), "/C".to_string()];
+ wrapped.extend(argv.iter().cloned());
+ spawn(&wrapped, dir, &log)
+ }
+ other => other,
+ }
+ .with_context(|| format!("couldn't start the agent ({}); is it installed and on PATH?", argv[0]))?;
+ if let Some(mut stdin) = child.stdin.take() {
+ stdin.write_all(prompt.as_bytes())?;
+ }
+ let status = child.wait()?;
+ let text = fs::read_to_string(log_path).unwrap_or_default();
+ ensure!(
+ status.success(),
+ "the agent exited with {status}. Log: {}\n{}",
+ log_path.display(),
+ crate::util::tail(&text, 15)
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn presets_and_custom() {
+ assert_eq!(super::argv("claude")[0], "claude");
+ assert_eq!(super::argv("codex"), ["codex", "exec", "--full-auto", "-"]);
+ assert_eq!(super::argv("aider --yes"), ["aider", "--yes"]);
+ }
+}
diff --git a/src/backend.rs b/src/backend.rs
new file mode 100644
index 0000000..f8f2e8b
--- /dev/null
+++ b/src/backend.rs
@@ -0,0 +1,277 @@
+//! What every language backend does, and the parts they share: building the crate and
+//! the marked blocks appended to source files.
+
+use crate::hotspot::Hotspot;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{output, tail};
+use crate::{node, python, ruby};
+use anyhow::{Context, Result, bail, ensure};
+use serde::{Deserialize, Serialize};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Lang {
+ #[default]
+ Python,
+ Node,
+ Ruby,
+}
+
+#[derive(Deserialize)]
+pub struct Profile {
+ pub wall: f64,
+ pub base: String,
+ pub functions: Vec<Hotspot>,
+}
+
+#[derive(Deserialize)]
+pub struct Recording {
+ pub calls: u64,
+ pub kept: usize,
+ pub skipped: usize,
+ pub unsupported: Vec<String>,
+}
+
+impl Lang {
+ pub fn detect(program: &str) -> Result<Lang> {
+ if python::is_python(program) {
+ Ok(Lang::Python)
+ } else if node::is_node(program) {
+ Ok(Lang::Node)
+ } else if ruby::is_ruby(program) {
+ Ok(Lang::Ruby)
+ } 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"
+ )
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Lang::Python => "Python",
+ Lang::Node => "JavaScript",
+ Lang::Ruby => "Ruby",
+ }
+ }
+
+ pub fn resolve(self, program: &str, root: &Path) -> Result<String> {
+ match self {
+ Lang::Python => python::resolve(program, root),
+ Lang::Node => node::resolve(program, root),
+ Lang::Ruby => ruby::resolve(program, root),
+ }
+ }
+
+ pub fn profile(self, ctx: &Ctx, exe: &str, args: &[String]) -> Result<Profile> {
+ match self {
+ Lang::Python => python::profile(ctx, exe, args),
+ Lang::Node => node::profile(ctx, exe, args),
+ Lang::Ruby => ruby::profile(ctx, exe, args),
+ }
+ }
+
+ pub fn record(
+ self,
+ ctx: &Ctx,
+ exe: &str,
+ args: &[String],
+ hs: &Hotspot,
+ out: &Path,
+ limit: usize,
+ ) -> Result<Recording> {
+ match self {
+ 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),
+ }
+ }
+
+ pub fn scaffold(self, ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ match self {
+ Lang::Python => python::scaffold(ctx, hs, helpers, port),
+ Lang::Node => node::scaffold(ctx, hs, helpers, port),
+ Lang::Ruby => ruby::scaffold(ctx, hs, helpers, port),
+ }
+ }
+
+ pub fn verify(self, ctx: &Ctx, port: &Port) -> Result<Verify> {
+ match self {
+ Lang::Python => python::verify(ctx, port),
+ Lang::Node => node::verify(ctx, port),
+ Lang::Ruby => ruby::verify(ctx, port),
+ }
+ }
+
+ pub fn enable(self, ctx: &Ctx, port: &Port) -> Result<()> {
+ match self {
+ Lang::Python => python::enable(ctx, port),
+ Lang::Node => node::enable(ctx, port),
+ Lang::Ruby => ruby::enable(ctx, port),
+ }
+ }
+
+ pub fn disable(self, ctx: &Ctx, port: &Port) -> Result<()> {
+ match self {
+ Lang::Python => python::disable(ctx, port),
+ Lang::Node => node::disable(ctx, port),
+ Lang::Ruby => ruby::disable(ctx, port),
+ }
+ }
+
+ /// (file cargo builds, name it gets in .fast/lib)
+ pub fn artifact(self, ext: &str) -> (String, String) {
+ let built = if cfg!(windows) {
+ format!("{ext}.dll")
+ } else if cfg!(target_os = "macos") {
+ format!("lib{ext}.dylib")
+ } else {
+ format!("lib{ext}.so")
+ };
+ let dest = match self {
+ 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(),
+ };
+ (built, dest)
+ }
+}
+
+/// Settings shared by every generated crate: tuned for the machine that builds it
+/// (.fast/lib is rebuilt per machine, never shipped), plus macOS extension linking.
+pub const CARGO_CONFIG: &str = "# Built for the machine that runs it: .fast/lib is rebuilt per machine, never shipped.\n\
+[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n\n\
+# Extensions on macOS resolve the host's symbols at load time.\n\
+[target.aarch64-apple-darwin]\nrustflags = [\"-C\", \"target-cpu=native\", \"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]\n\n\
+[target.x86_64-apple-darwin]\nrustflags = [\"-C\", \"target-cpu=native\", \"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]\n";
+
+pub const RELEASE_PROFILE: &str = "[profile.release]\nopt-level = 3\nlto = \"fat\"\ncodegen-units = 1\n\n\
+# A crate of its own, even inside another Cargo workspace.\n[workspace]\n";
+
+fn compiler_errors(log: &str) -> String {
+ let noise =
+ ["Compiling", "Finished", "Updating", "Locking", "Downloading", "Downloaded", "Blocking", "Adding", "Checking"];
+ let kept: Vec<&str> = log.lines().filter(|l| !noise.iter().any(|n| l.trim_start().starts_with(n))).collect();
+ tail(&kept.join("\n"), 60)
+}
+
+/// Release-build a port into .fast/lib. Ok(Err(log)) when it doesn't compile.
+/// Every port shares one target dir, so dependencies compile once per project.
+pub fn build(ctx: &Ctx, port: &Port) -> Result<std::result::Result<PathBuf, String>> {
+ let exe = ctx.runtime()?;
+ let dir = ctx.crate_dir(port);
+ ensure!(dir.join("Cargo.toml").exists(), "{} has no crate yet: run fast-anything port {}", port.id, port.id);
+ let target = ctx.fast.join("target");
+ let mut cmd = Command::new("cargo");
+ cmd.args(["build", "--release", "--message-format=short"]).current_dir(&dir).env("CARGO_TARGET_DIR", &target);
+ if port.lang == Lang::Python {
+ cmd.env("PYO3_PYTHON", exe);
+ }
+ let out = output(&mut cmd, "cargo (install Rust from https://rustup.rs)")?;
+ if !out.status.success() {
+ return Ok(Err(compiler_errors(&String::from_utf8_lossy(&out.stderr))));
+ }
+ let (built, name) = port.lang.artifact(&port.ext);
+ let lib_dir = ctx.lib_dir();
+ fs::create_dir_all(&lib_dir)?;
+ let dest = lib_dir.join(name);
+ fs::copy(target.join("release").join(&built), &dest)
+ .with_context(|| format!("copying {built} into .fast/lib (is the app still running?)"))?;
+ Ok(Ok(dest))
+}
+
+// ------------------------------------------------------------------ marked blocks
+
+pub fn markers(comment: &str, id: &str) -> (String, String) {
+ (format!("{comment} >>> fast-anything: {id} >>>"), format!("{comment} <<< fast-anything: {id} <<<"))
+}
+
+fn newline(text: &str) -> &'static str {
+ if text.contains("\r\n") { "\r\n" } else { "\n" }
+}
+
+/// Remove the block for id; the rest of the file comes back byte for byte.
+pub fn strip_marked(text: &str, comment: &str, id: &str) -> String {
+ let (begin, end) = markers(comment, id);
+ let Some(start) = text.find(&begin) else { return text.to_string() };
+ let Some(len) = text[start..].find(&end) else { return text.to_string() };
+ let nl = newline(text);
+ let rest = &text[start + len + end.len()..];
+ let rest = rest.strip_prefix(nl).unwrap_or(rest);
+ if rest.is_empty() {
+ // appended at the end, after one blank line
+ let before = &text[..start];
+ before.strip_suffix(nl).unwrap_or(before).to_string()
+ } else {
+ // inserted before other code, followed by one blank line
+ format!("{}{}", &text[..start], rest.strip_prefix(nl).unwrap_or(rest))
+ }
+}
+
+fn block(text: &str, comment: &str, id: &str, body: &str) -> String {
+ let (begin, end) = markers(comment, id);
+ format!("{begin}\n{body}\n{end}").replace('\n', newline(text))
+}
+
+/// Append (or replace) the block for id at the end of the file, after one blank line.
+pub fn append_marked(text: &str, comment: &str, id: &str, body: &str) -> String {
+ let text = strip_marked(text, comment, id);
+ let nl = newline(&text);
+ let gap = if text.ends_with('\n') { nl.to_string() } else { format!("{nl}{nl}") };
+ format!("{text}{gap}{}{nl}", block(&text, comment, id, body))
+}
+
+/// Insert (or replace) the block for id right before the line at byte offset at.
+pub fn insert_marked(text: &str, comment: &str, id: &str, body: &str, at: impl Fn(&str) -> Option<usize>) -> String {
+ let text = strip_marked(text, comment, id);
+ let Some(at) = at(&text) else { return append_marked(&text, comment, id, body) };
+ let nl = newline(&text);
+ format!("{}{}{nl}{nl}{}", &text[..at], block(&text, comment, id, body), &text[at..])
+}
+
+/// Byte offset of the first top-level line that starts with one of the prefixes.
+pub fn line_starting(text: &str, prefixes: &[&str]) -> Option<usize> {
+ let mut offset = 0;
+ for line in text.split_inclusive('\n') {
+ let squashed: String = line.chars().filter(|c| !c.is_whitespace()).collect();
+ let top_level = !line.starts_with([' ', '\t']);
+ if top_level && prefixes.iter().any(|p| squashed.starts_with(p)) {
+ return Some(offset);
+ }
+ offset += line.len();
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn blocks_come_out_byte_for_byte() {
+ let guard = |t: &str| line_starting(t, &["if__name__==\"__main__\":", "if__name__=='__main__':"]);
+ for original in ["a = 1\n", "a = 1\r\n", "a = 1\n\n\nif __name__ == \"__main__\":\n main()\n", "x"] {
+ let appended = append_marked(original, "#", "m.f", "f = g");
+ assert!(appended.contains("# >>> fast-anything: m.f >>>"));
+ assert_eq!(
+ strip_marked(&appended, "#", "m.f"),
+ original.to_string() + if original == "x" { "\n" } else { "" }
+ );
+ let inserted = insert_marked(original, "#", "m.f", "f = g", guard);
+ assert_eq!(insert_marked(&inserted, "#", "m.f", "f = g", guard), inserted, "idempotent");
+ let back = strip_marked(&inserted, "#", "m.f");
+ assert_eq!(back.trim_end(), original.trim_end());
+ if original.contains("__main__") {
+ assert_eq!(back, original);
+ assert!(inserted.find(">>>").unwrap() < inserted.find("if __name__").unwrap());
+ }
+ }
+ let two = append_marked(&append_marked("a\n", "#", "one", "1"), "#", "two", "2");
+ assert_eq!(strip_marked(&strip_marked(&two, "#", "one"), "#", "two"), "a\n");
+ }
+}
diff --git a/src/bench.rs b/src/bench.rs
new file mode 100644
index 0000000..0b63502
--- /dev/null
+++ b/src/bench.rs
@@ -0,0 +1,112 @@
+//! Times the whole app: original Python vs Rust ports, interleaved so drift hits both equally.
+
+use crate::backend::Lang;
+use crate::python::DISABLE_ENV;
+use crate::state::Ctx;
+use crate::{ui, util};
+use anyhow::{Context, Result, ensure};
+use serde::{Deserialize, Serialize};
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Stats {
+ pub median: f64,
+ pub mean: f64,
+ pub min: f64,
+ pub max: f64,
+ pub stddev: f64,
+}
+
+impl Stats {
+ pub fn of(xs: &[f64]) -> Stats {
+ if xs.is_empty() {
+ return Stats::default();
+ }
+ let mut v = xs.to_vec();
+ v.sort_by(f64::total_cmp);
+ let n = v.len() as f64;
+ let mean = v.iter().sum::<f64>() / n;
+ let median = if v.len() % 2 == 1 { v[v.len() / 2] } else { (v[v.len() / 2 - 1] + v[v.len() / 2]) / 2.0 };
+ let var = v.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n;
+ Stats { median, mean, min: v[0], max: v[v.len() - 1], stddev: var.sqrt() }
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct BenchResult {
+ pub lang: Lang,
+ pub command: Vec<String>,
+ pub runs: usize,
+ pub ports: Vec<String>,
+ pub before: Stats,
+ pub after: Stats,
+ pub speedup: f64,
+}
+
+fn time_once(ctx: &Ctx, python: &str, args: &[String], original: bool) -> Result<f64> {
+ let mut cmd = Command::new(python);
+ cmd.args(args).current_dir(&ctx.root).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());
+ if original {
+ cmd.env(DISABLE_ENV, "1");
+ } else {
+ cmd.env_remove(DISABLE_ENV);
+ }
+ let start = Instant::now();
+ let out = cmd.output().context("running the app")?;
+ let took = start.elapsed().as_secs_f64();
+ ensure!(
+ out.status.success(),
+ "the app failed ({}) with the {} version:\n{}",
+ out.status,
+ if original { ctx.state.lang.label() } else { "Rust" },
+ util::tail(&String::from_utf8_lossy(&out.stderr), 20)
+ );
+ Ok(took)
+}
+
+pub fn run(ctx: &Ctx, runs: usize) -> Result<BenchResult> {
+ let python = ctx.runtime()?;
+ let args = &ctx.state.command[1..];
+ 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");
+ }
+ ui::step(format!(
+ "timing {} ({runs} runs each, {} vs Rust, interleaved)",
+ ui::bold(ctx.state.command.join(" ")),
+ ctx.state.lang.label()
+ ));
+ time_once(ctx, python, args, true)?;
+ time_once(ctx, python, args, false)?;
+ let (mut before, mut after) = (Vec::with_capacity(runs), Vec::with_capacity(runs));
+ for i in 0..runs {
+ if i % 2 == 0 {
+ before.push(time_once(ctx, python, args, true)?);
+ after.push(time_once(ctx, python, args, false)?);
+ } else {
+ after.push(time_once(ctx, python, args, false)?);
+ before.push(time_once(ctx, python, args, true)?);
+ }
+ }
+ let (before, after) = (Stats::of(&before), Stats::of(&after));
+ let speedup = if after.median > 0.0 { before.median / after.median } else { 0.0 };
+ Ok(BenchResult { lang: ctx.state.lang, command: ctx.state.command.clone(), runs, ports, before, after, speedup })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::Stats;
+
+ #[test]
+ fn stats() {
+ let s = Stats::of(&[3.0, 1.0, 2.0, 10.0]);
+ assert_eq!(s.median, 2.5);
+ assert_eq!(s.min, 1.0);
+ assert_eq!(s.max, 10.0);
+ assert_eq!(s.mean, 4.0);
+ assert_eq!(Stats::of(&[5.0]).median, 5.0);
+ }
+}
diff --git a/src/doctor.rs b/src/doctor.rs
new file mode 100644
index 0000000..2a9834f
--- /dev/null
+++ b/src/doctor.rs
@@ -0,0 +1,69 @@
+//! fast-anything doctor: is everything a port needs installed?
+
+use crate::ui::{self, bold, dim, green, red, yellow};
+use anyhow::{Result, ensure};
+use std::process::Command;
+
+fn version(program: &str, args: &[&str]) -> Option<String> {
+ let run = |p: &str| Command::new(p).args(args).output().ok().filter(|o| o.status.success());
+ let out = run(program).or_else(|| if cfg!(windows) { run(&format!("{program}.cmd")) } else { None })?;
+ let text = String::from_utf8_lossy(if out.stdout.is_empty() { &out.stderr } else { &out.stdout }).into_owned();
+ Some(text.lines().next().unwrap_or("").trim().to_string())
+}
+
+struct Check {
+ name: &'static str,
+ found: Option<String>,
+ need: &'static str,
+ hint: &'static str,
+}
+
+pub fn run() -> Result<()> {
+ let python = version("python", &["--version"]).or_else(|| version("python3", &["--version"]));
+ let checks = [
+ Check { name: "cargo", found: version("cargo", &["--version"]), need: "required", hint: "https://rustup.rs" },
+ Check { name: "python", found: python, need: "for Python apps (3.10+)", hint: "https://python.org" },
+ Check {
+ name: "node",
+ found: version("node", &["--version"]),
+ need: "for JS/TS apps (22+)",
+ hint: "https://nodejs.org",
+ },
+ Check {
+ name: "ruby",
+ found: version("ruby", &["--version"]),
+ need: "for Ruby apps (3.3+)",
+ hint: "https://ruby-lang.org",
+ },
+ Check {
+ name: "claude",
+ found: version("claude", &["--version"]),
+ need: "--agent claude",
+ hint: "https://claude.com/claude-code",
+ },
+ Check {
+ name: "codex",
+ found: version("codex", &["--version"]),
+ need: "--agent codex",
+ hint: "npm i -g @openai/codex",
+ },
+ ];
+ for c in &checks {
+ match &c.found {
+ Some(v) => ui::line(format!(" {} {:<8} {}", green("✓"), bold(c.name), dim(v))),
+ None if c.need == "required" => {
+ ui::line(format!(" {} {:<8} missing, {}: {}", red("✗"), bold(c.name), c.need, c.hint))
+ }
+ None => ui::line(format!(
+ " {} {:<8} {}",
+ yellow("·"),
+ c.name,
+ dim(format!("not found ({}): {}", c.need, c.hint))
+ )),
+ }
+ }
+ 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");
+ ui::ok("ready");
+ Ok(())
+}
diff --git a/src/hotspot.rs b/src/hotspot.rs
new file mode 100644
index 0000000..f78caa0
--- /dev/null
+++ b/src/hotspot.rs
@@ -0,0 +1,137 @@
+//! What a scan finds: functions, how much of the run they cost, and whether they can move to Rust.
+
+use serde::{Deserialize, Serialize};
+
+/// Functions under this share of the run aren't worth porting.
+pub const WORTH_IT: f64 = 0.02;
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Param {
+ pub name: String,
+ pub annotation: Option<String>,
+ /// Default value as source text, e.g. "2" or "None".
+ pub default: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Hotspot {
+ pub id: String,
+ pub file: String,
+ pub line: u32,
+ pub end_line: u32,
+ pub name: String,
+ pub qualname: String,
+ pub module: Option<String>,
+ pub kind: String,
+ pub ncalls: u64,
+ pub tottime: f64,
+ pub cumtime: f64,
+ /// Share of the run spent in this function, callees included.
+ pub share: f64,
+ /// 0 = can't be ported, 1 = ideal candidate.
+ pub portability: f64,
+ pub score: f64,
+ pub blockers: Vec<String>,
+ pub warnings: Vec<String>,
+ pub params: Vec<Param>,
+ pub returns: Option<String>,
+ pub source: String,
+ /// Functions from the same file this one calls.
+ pub calls: Vec<String>,
+ /// A portable caller that takes about as long: porting it covers this one too,
+ /// and saves a Python/JS -> Rust crossing per call.
+ pub covered_by: Option<String>,
+ /// Ruby: the module (or Object) whose method this is, as a Ruby expression.
+ pub owner: Option<String>,
+}
+
+impl Hotspot {
+ pub fn portable(&self) -> bool {
+ self.blockers.is_empty()
+ }
+
+ pub fn worth_it(&self) -> bool {
+ self.portable() && self.covered_by.is_none() && self.share >= WORTH_IT
+ }
+}
+
+/// Give each function an id and a score (time share x portability), best first.
+pub fn rank(mut list: Vec<Hotspot>, wall: f64) -> Vec<Hotspot> {
+ for h in &mut list {
+ h.id = match h.module.as_deref() {
+ Some(m) if m != "__main__" => format!("{m}.{}", h.qualname),
+ _ => format!("{}:{}", h.file, h.qualname),
+ };
+ h.share = if wall > 0.0 { (h.cumtime / wall).clamp(0.0, 1.0) } else { 0.0 };
+ h.portability = if h.portable() { h.portability.clamp(0.0, 1.0) } else { 0.0 };
+ h.score = h.share * h.portability;
+ }
+ // Prefer the outermost portable function: one call into Rust instead of one per inner call.
+ let callers: Vec<(String, String, f64, Vec<String>)> = list
+ .iter()
+ .filter(|h| h.portable())
+ .map(|h| (h.id.clone(), h.file.clone(), h.share, h.calls.clone()))
+ .collect();
+ for h in list.iter_mut().filter(|h| h.portable()) {
+ let cover = callers
+ .iter()
+ .filter(|(id, file, share, calls)| {
+ *id != h.id && *file == h.file && calls.contains(&h.name) && *share >= 0.9 * h.share
+ })
+ .max_by(|a, b| a.2.total_cmp(&b.2));
+ if let Some((id, ..)) = cover {
+ h.covered_by = Some(id.clone());
+ h.score = 0.0;
+ }
+ }
+ list.sort_by(|a, b| b.score.total_cmp(&a.score).then(b.share.total_cmp(&a.share)));
+ list
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn hs(name: &str, module: Option<&str>, cumtime: f64, portability: f64, blocked: bool) -> Hotspot {
+ Hotspot {
+ name: name.into(),
+ qualname: name.into(),
+ file: "app.py".into(),
+ module: module.map(Into::into),
+ cumtime,
+ portability,
+ blockers: if blocked { vec!["does I/O: print".into()] } else { vec![] },
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn outer_loop_covers_inner_function() {
+ let mut outer = hs("find_duplicates", Some("fuzzy"), 9.9, 1.0, false);
+ outer.calls = vec!["lev".into()];
+ let ranked = rank(vec![hs("lev", Some("fuzzy"), 9.5, 1.0, false), outer], 10.0);
+ assert_eq!(ranked[0].id, "fuzzy.find_duplicates");
+ assert_eq!(ranked[1].covered_by.as_deref(), Some("fuzzy.find_duplicates"));
+ assert!(!ranked[1].worth_it());
+ }
+
+ #[test]
+ fn portable_beats_bigger_but_blocked() {
+ let ranked = rank(
+ vec![
+ hs("main", Some("__main__"), 10.0, 1.0, true),
+ hs("lev", Some("fuzzy"), 9.0, 1.0, false),
+ hs("norm", Some("fuzzy"), 0.1, 1.0, false),
+ ],
+ 10.0,
+ );
+ assert_eq!(ranked[0].id, "fuzzy.lev");
+ assert!((ranked[0].share - 0.9).abs() < 1e-9);
+ assert_eq!(ranked[1].id, "fuzzy.norm");
+ assert_eq!(ranked[2].id, "app.py:main");
+ assert_eq!(ranked[2].score, 0.0);
+ assert!(!ranked[1].worth_it());
+ }
+}
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..0b00c4a
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,179 @@
+//! fast-anything: find the slow 5% of your app, rewrite just that in Rust, prove it behaves the same.
+
+mod agent;
+mod backend;
+mod bench;
+mod doctor;
+mod hotspot;
+mod mcp;
+mod node;
+mod pipeline;
+mod python;
+mod report;
+mod ruby;
+mod show;
+mod state;
+mod ui;
+mod util;
+
+use anyhow::{Result, bail};
+use clap::{Parser, Subcommand};
+use std::path::{Path, PathBuf};
+use std::process::ExitCode;
+
+#[derive(Parser)]
+#[command(name = "fast-anything", version, about, arg_required_else_help = true)]
+#[command(
+ after_help = "One command:\n fast-anything go --agent claude -- python app.py\n\nStep by step:\n fast-anything scan -- python app.py\n fast-anything port\n fast-anything verify\n fast-anything enable <id>\n fast-anything bench"
+)]
+struct Cli {
+ /// Project folder (default: the current folder)
+ #[arg(short = 'C', long = "dir", global = true, default_value = ".")]
+ dir: PathBuf,
+ #[command(subcommand)]
+ cmd: Cmd,
+}
+
+#[derive(Subcommand)]
+enum Cmd {
+ /// Everything in one go: scan, port the hottest functions with your agent, verify, switch on, benchmark
+ Go {
+ /// Coding agent that writes the Rust: claude, codex, or any command that reads a prompt on stdin
+ #[arg(long)]
+ agent: Option<String>,
+ /// How many hot functions to port
+ #[arg(long, default_value_t = 1)]
+ top: usize,
+ /// Agent attempts per function before giving up
+ #[arg(long, default_value_t = 3)]
+ attempts: usize,
+ /// Benchmark runs
+ #[arg(long, default_value_t = 5)]
+ runs: usize,
+ /// Real calls to record per function
+ #[arg(long, default_value_t = 500)]
+ samples: usize,
+ /// How you run your app, after --
+ #[arg(last = true, required = true)]
+ command: Vec<String>,
+ },
+ /// Run your app under a profiler and rank what's worth porting
+ Scan {
+ /// How you run your app, after --
+ #[arg(last = true, required = true)]
+ command: Vec<String>,
+ },
+ /// Record a function's real calls and set up its Rust crate (default: the top candidate)
+ Port {
+ id: Option<String>,
+ /// Have this coding agent write the port right away
+ #[arg(long)]
+ agent: Option<String>,
+ #[arg(long, default_value_t = 3)]
+ attempts: usize,
+ #[arg(long, default_value_t = 500)]
+ samples: usize,
+ },
+ /// Build the Rust port and replay every recorded call against it
+ Verify { id: Option<String> },
+ /// Switch your app over to the verified Rust port
+ Enable {
+ id: Option<String>,
+ /// Enable even if it hasn't passed verify
+ #[arg(long)]
+ force: bool,
+ },
+ /// Switch back to the original code
+ Disable { id: Option<String> },
+ /// Rebuild every port (after cloning, or a toolchain upgrade)
+ Build,
+ /// Time your app with the originals vs the Rust ports
+ Bench {
+ #[arg(long, default_value_t = 5)]
+ runs: usize,
+ },
+ /// Write a shareable report (markdown + SVG card)
+ Report,
+ /// Show the last scan and every port
+ Status,
+ /// Check that Rust, Python/Node and your agents are installed
+ Doctor,
+ /// Run as an MCP server on stdio (for Claude Code, Codex, Cursor, ...)
+ Mcp,
+}
+
+fn main() -> ExitCode {
+ let cli = Cli::parse();
+ let root = util::absolute(&cli.dir);
+ match run(cli.cmd, &root) {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(e) => {
+ ui::error(format!("{e:#}"));
+ ExitCode::FAILURE
+ }
+ }
+}
+
+fn run(cmd: Cmd, root: &Path) -> Result<()> {
+ if matches!(cmd, Cmd::Mcp) {
+ return mcp::serve();
+ }
+ ui::banner();
+ match cmd {
+ Cmd::Go { agent, top, attempts, runs, samples, command } => {
+ pipeline::go(root, command, agent.as_deref(), top, attempts, runs, samples)
+ }
+ Cmd::Scan { command } => {
+ show::scan(&pipeline::scan(root, command)?);
+ Ok(())
+ }
+ Cmd::Port { id, agent, attempts, samples } => {
+ let out = pipeline::port(root, id.as_deref(), samples)?;
+ show::port(&out, agent.is_none());
+ if let Some(agent) = agent {
+ let v = pipeline::agent_port(root, &out.id, &agent, attempts)?;
+ if !v.ok() {
+ bail!("{agent} couldn't get {} right in {attempts} attempts", out.id);
+ }
+ show::next(&format!("fast-anything enable {}", out.id));
+ }
+ Ok(())
+ }
+ Cmd::Verify { id } => {
+ let (id, v) = pipeline::verify(root, id.as_deref())?;
+ show::verify(&id, &v);
+ if !v.ok() {
+ bail!("{id} doesn't match the original yet");
+ }
+ show::next(&format!("fast-anything enable {id}"));
+ Ok(())
+ }
+ Cmd::Enable { id, force } => {
+ let id = pipeline::enable(root, id.as_deref(), force)?;
+ ui::ok(format!("{} now runs in Rust", ui::bold(&id)));
+ show::next("fast-anything bench");
+ Ok(())
+ }
+ Cmd::Disable { id } => {
+ let id = pipeline::disable(root, id.as_deref())?;
+ ui::ok(format!("{} is back to the original code", ui::bold(&id)));
+ Ok(())
+ }
+ Cmd::Build => pipeline::build_all(root),
+ Cmd::Bench { runs } => {
+ show::bench(&pipeline::bench(root, runs)?);
+ show::next("fast-anything report");
+ Ok(())
+ }
+ Cmd::Report => {
+ show::report(&pipeline::report(root)?);
+ Ok(())
+ }
+ Cmd::Status => {
+ show::status(&state::Ctx::open(root)?);
+ Ok(())
+ }
+ Cmd::Doctor => doctor::run(),
+ Cmd::Mcp => unreachable!(),
+ }
+}
diff --git a/src/mcp.rs b/src/mcp.rs
new file mode 100644
index 0000000..9354a22
--- /dev/null
+++ b/src/mcp.rs
@@ -0,0 +1,181 @@
+//! MCP server on stdio (JSON-RPC 2.0, one message per line). Lets any agent drive fast-anything.
+
+use crate::{pipeline, state, ui};
+use anyhow::Result;
+use serde_json::{Value, json};
+use std::io::{BufRead, Write};
+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) \
+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.";
+
+fn tools() -> Value {
+ let path = json!({ "type": "string", "description": "Project folder (default: the server's working folder)" });
+ let id = json!({ "type": "string", "description": "Function id from the scan, e.g. fuzzy.levenshtein" });
+ let tool = |name: &str, description: &str, properties: Value, required: Value| {
+ json!({ "name": name, "description": description,
+ "inputSchema": { "type": "object", "properties": properties, "required": required } })
+ };
+ json!([
+ 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"])
+ ),
+ tool(
+ "fast_port",
+ "Record real calls to a hot function and create its Rust crate. Returns the task: write src/lib.rs, then call fast_verify.",
+ json!({ "id": id, "samples": { "type": "integer", "default": 500 }, "path": path }),
+ json!([])
+ ),
+ tool(
+ "fast_verify",
+ "Release-build the Rust port and replay every recorded call against it. Returns compile errors or mismatches to fix.",
+ json!({ "id": id, "path": path }),
+ json!([])
+ ),
+ tool(
+ "fast_enable",
+ "Switch the app over to a verified Rust port (reversible).",
+ json!({ "id": id, "path": path, "force": { "type": "boolean" } }),
+ json!([])
+ ),
+ tool(
+ "fast_disable",
+ "Switch a function back to the original Python.",
+ json!({ "id": id, "path": path }),
+ json!([])
+ ),
+ tool(
+ "fast_bench",
+ "Time the whole app: original Python vs Rust ports.",
+ json!({ "runs": { "type": "integer", "default": 5 }, "path": path }),
+ json!([])
+ ),
+ tool(
+ "fast_report",
+ "Write .fast/report.md and a shareable .fast/report.svg card.",
+ json!({ "path": path }),
+ json!([])
+ ),
+ tool("fast_status", "Show the last scan and every port.", json!({ "path": path }), json!([])),
+ ])
+}
+
+fn call(params: &Value) -> Result<Value> {
+ let args = &params["arguments"];
+ let root = args["path"].as_str().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
+ let id = args["id"].as_str();
+ Ok(match params["name"].as_str().unwrap_or_default() {
+ "fast_scan" => {
+ let command: Vec<String> = args["command"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
+ .unwrap_or_default();
+ let scan = pipeline::scan(&root, command)?;
+ let top: Vec<Value> = scan
+ .hotspots
+ .iter()
+ .take(10)
+ .map(|h| {
+ json!({ "id": h.id, "share": h.share, "calls": h.ncalls, "worth_porting": h.worth_it(),
+ "blockers": h.blockers, "warnings": h.warnings, "file": h.file, "line": h.line })
+ })
+ .collect();
+ json!({ "wall_seconds": scan.wall, "hotspots": top })
+ }
+ "fast_port" => {
+ let samples = args["samples"].as_u64().unwrap_or(500) as usize;
+ serde_json::to_value(pipeline::port(&root, id, samples)?)?
+ }
+ "fast_verify" => {
+ let (id, v) = pipeline::verify(&root, id)?;
+ let mut out = serde_json::to_value(&v)?;
+ out["id"] = json!(id);
+ out["ok"] = json!(v.ok());
+ if !v.ok() {
+ out["fix"] = json!(pipeline::feedback(&v));
+ }
+ out
+ }
+ "fast_enable" => json!({ "enabled": pipeline::enable(&root, id, args["force"].as_bool().unwrap_or(false))? }),
+ "fast_disable" => json!({ "disabled": pipeline::disable(&root, id)? }),
+ "fast_bench" => serde_json::to_value(pipeline::bench(&root, args["runs"].as_u64().unwrap_or(5) as usize)?)?,
+ "fast_report" => serde_json::to_value(pipeline::report(&root)?)?,
+ "fast_status" => {
+ let ctx = state::Ctx::open(&root)?;
+ json!({ "command": ctx.state.command, "ports": ctx.state.ports, "bench": ctx.state.bench })
+ }
+ other => anyhow::bail!("unknown tool {other}"),
+ })
+}
+
+fn handle(msg: &Value) -> Option<Value> {
+ let id = msg.get("id")?.clone();
+ let params = &msg["params"];
+ let result = match msg["method"].as_str().unwrap_or_default() {
+ "initialize" => json!({
+ "protocolVersion": params["protocolVersion"].as_str().unwrap_or(PROTOCOL),
+ "capabilities": { "tools": {} },
+ "serverInfo": { "name": "fast-anything", "version": env!("CARGO_PKG_VERSION") },
+ "instructions": INSTRUCTIONS,
+ }),
+ "ping" => json!({}),
+ "tools/list" => json!({ "tools": tools() }),
+ "tools/call" => match call(params) {
+ Ok(v) => {
+ json!({ "content": [{ "type": "text", "text": serde_json::to_string_pretty(&v).unwrap_or_default() }] })
+ }
+ Err(e) => json!({ "content": [{ "type": "text", "text": format!("{e:#}") }], "isError": true }),
+ },
+ method => {
+ return Some(
+ json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": format!("unknown method {method}") } }),
+ );
+ }
+ };
+ Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }))
+}
+
+pub fn serve() -> Result<()> {
+ ui::set_quiet(true);
+ let stdin = std::io::stdin();
+ let mut stdout = std::io::stdout().lock();
+ for line in stdin.lock().lines() {
+ let line = line?;
+ if line.trim().is_empty() {
+ continue;
+ }
+ let reply = match serde_json::from_str::<Value>(&line) {
+ Ok(msg) => handle(&msg),
+ Err(e) => {
+ Some(json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": e.to_string() } }))
+ }
+ };
+ if let Some(reply) = reply {
+ writeln!(stdout, "{reply}")?;
+ stdout.flush()?;
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn handshake_and_listing() {
+ let init = handle(&json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-11-25" } })).unwrap();
+ assert_eq!(init["result"]["protocolVersion"], "2025-11-25");
+ let list = handle(&json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list" })).unwrap();
+ assert_eq!(list["result"]["tools"].as_array().unwrap().len(), 8);
+ assert!(handle(&json!({ "jsonrpc": "2.0", "method": "notifications/initialized" })).is_none());
+ let bad = handle(&json!({ "jsonrpc": "2.0", "id": 3, "method": "nope" })).unwrap();
+ assert_eq!(bad["error"]["code"], -32601);
+ }
+}
diff --git a/src/node.rs b/src/node.rs
new file mode 100644
index 0000000..478f2c5
--- /dev/null
+++ b/src/node.rs
@@ -0,0 +1,519 @@
+//! Node.js backend (JavaScript and TypeScript): V8 CPU profile, call recording through a temporary
+//! block appended to the module, a napi-rs crate, and a reversible shim that rebinds the function.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::Hotspot;
+use crate::python::DISABLE_ENV;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{combined, forward_slashes, output, relative, slug, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde_json::{Value, json};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, Stdio};
+
+const RUNNER: &str = include_str!("node/runner.mjs");
+const RECORDER: &str = include_str!("node/recorder.cjs");
+
+pub fn is_node(program: &str) -> bool {
+ let stem = Path::new(program).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase();
+ stem == "node" || stem == "nodejs"
+}
+
+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(["-p", "process.execPath + '\\n' + process.versions.node"]).current_dir(root),
+ "node",
+ )?;
+ ensure!(out.status.success(), "{program} failed:\n{}", tail(&combined(&out), 5));
+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
+ let mut lines = text.lines();
+ let exe = lines.next().unwrap_or_default().trim().to_string();
+ let major: u32 = lines.next().unwrap_or_default().split('.').next().and_then(|m| m.parse().ok()).unwrap_or(0);
+ ensure!(major >= 22, "Node.js 22 or newer is needed (found {major})");
+ Ok(exe)
+}
+
+/// The script in "node [flags] script.js args".
+fn entry(args: &[String]) -> Option<&String> {
+ let mut it = args.iter();
+ while let Some(a) = it.next() {
+ if matches!(
+ a.as_str(),
+ "-r" | "--require" | "--import" | "--loader" | "--experimental-loader" | "-C" | "--conditions"
+ ) {
+ it.next();
+ } else if !a.starts_with('-') {
+ return Some(a);
+ }
+ }
+ None
+}
+
+fn runner(ctx: &Ctx, node: &str, mode: &str, job: Value) -> Result<Output> {
+ let script = ctx.fast.join("runner.mjs");
+ fs::write(&script, RUNNER)?;
+ let job_path = ctx.fast.join(format!("job-{mode}.json"));
+ fs::write(&job_path, serde_json::to_vec_pretty(&job)?)?;
+ let out = output(
+ Command::new(node).arg(&script).arg(mode).arg(&job_path).current_dir(&ctx.root).stdin(Stdio::null()),
+ "node",
+ )?;
+ if !out.status.success() {
+ bail!("the node {mode} step failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ }
+ Ok(out)
+}
+
+pub fn profile(ctx: &Ctx, node: &str, args: &[String]) -> Result<Profile> {
+ let script = entry(args).context("name the script to run, e.g. fast-anything scan -- node app.js")?;
+ let dir = ctx.fast.join("cpuprof");
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir)?;
+ let out = output(
+ Command::new(node)
+ .args(["--cpu-prof", "--cpu-prof-interval", "250", "--cpu-prof-dir"])
+ .arg(&dir)
+ .args(args)
+ .current_dir(&ctx.root)
+ .stdin(Stdio::null()),
+ "node",
+ )?;
+ ensure!(out.status.success(), "the app failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ let result = ctx.fast.join("profile.json");
+ let job = json!({ "root": ctx.root, "dir": dir, "entry": ctx.root.join(script), "out": result });
+ runner(ctx, node, "profile", job)?;
+ serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")
+}
+
+/// Re-run the app with a recorder wrapped around the function. The module gets a temporary
+/// block appended (a copy waits in .fast/backup) and is restored byte for byte afterwards.
+pub fn record(ctx: &Ctx, node: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
+ let file = ctx.root.join(&hs.file);
+ let original = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;
+ let backup_dir = ctx.fast.join("backup");
+ fs::create_dir_all(&backup_dir)?;
+ let backup = backup_dir.join(slug(&hs.file));
+ fs::write(&backup, &original)?;
+
+ let f = &hs.name;
+ let wrap = format!("{f} = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap({f}) : {f};");
+ fs::write(&file, backend::append_marked(&original, "//", &format!("recording {}", hs.id), &wrap))?;
+ let recorder = ctx.fast.join("recorder.cjs");
+ fs::write(&recorder, RECORDER)?;
+ let meta = out.with_extension("meta.json");
+ let run = output(
+ Command::new(node)
+ .arg("--require")
+ .arg(&recorder)
+ .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()),
+ "node",
+ );
+ fs::write(&file, &original)
+ .with_context(|| format!("restoring {} (a copy is in {})", hs.file, backup.display()))?;
+ let _ = fs::remove_file(&backup);
+ let run = run?;
+ ensure!(run.status.success(), "the app failed while recording ({}):\n{}", run.status, tail(&combined(&run), 30));
+ serde_json::from_str(&fs::read_to_string(&meta)?).context("reading the recording summary")
+}
+
+// ------------------------------------------------------------------ the napi-rs crate
+
+fn split_union(s: &str) -> Vec<String> {
+ let (mut depth, mut cur, mut out) = (0i32, String::new(), vec![]);
+ for c in s.chars() {
+ match c {
+ '<' | '[' | '(' | '{' => depth += 1,
+ '>' | ']' | ')' | '}' => depth -= 1,
+ '|' if depth == 0 => {
+ out.push(cur.trim().to_string());
+ cur.clear();
+ continue;
+ }
+ _ => {}
+ }
+ cur.push(c);
+ }
+ out.push(cur.trim().to_string());
+ out.into_iter().filter(|p| !p.is_empty()).collect()
+}
+
+const TYPED_ARRAYS: &[&str] = &[
+ "Float64Array",
+ "Float32Array",
+ "Int32Array",
+ "Uint32Array",
+ "Int16Array",
+ "Uint16Array",
+ "Int8Array",
+ "Uint8Array",
+];
+
+/// Rust type for a TypeScript annotation, if there's an obvious one.
+pub fn rust_type(annotation: &str) -> Option<String> {
+ let a = annotation.split_whitespace().collect::<Vec<_>>().join(" ");
+ let parts = split_union(&a);
+ let solid: Vec<&String> = parts.iter().filter(|p| *p != "null" && *p != "undefined").collect();
+ if solid.len() < parts.len() {
+ return match solid.as_slice() {
+ [one] => rust_type(one).map(|t| format!("Option<{t}>")),
+ _ => None,
+ };
+ }
+ if parts.len() != 1 {
+ return None;
+ }
+ let a = a.trim();
+ Some(match a {
+ "number" => "f64".into(),
+ "string" => "String".into(),
+ "boolean" => "bool".into(),
+ "void" | "undefined" => "()".into(),
+ t if TYPED_ARRAYS.contains(&t) => t.into(),
+ _ => {
+ let inner = a
+ .strip_suffix("[]")
+ .map(|x| x.trim_start_matches("readonly ").to_string())
+ .or_else(|| a.strip_prefix("Array<").and_then(|x| x.strip_suffix('>')).map(String::from))
+ .or_else(|| a.strip_prefix("ReadonlyArray<").and_then(|x| x.strip_suffix('>')).map(String::from));
+ let tuple = a
+ .strip_prefix('[')
+ .and_then(|x| x.strip_suffix(']'))
+ .map(|x| x.split(',').map(|p| rust_type(p.trim())).collect::<Option<Vec<String>>>());
+ if let Some(Some(parts)) = tuple {
+ // A JS tuple is an array; a same-typed one maps to a Vec.
+ if parts.is_empty() || parts.iter().any(|p| p != &parts[0]) {
+ return None;
+ }
+ format!("Vec<{}>", parts[0])
+ } else if let Some(inner) = inner {
+ format!("Vec<{}>", rust_type(&inner)?)
+ } else {
+ let v = a.strip_prefix("Record<string,").and_then(|x| x.strip_suffix('>'))?;
+ format!("std::collections::HashMap<String, {}>", rust_type(v.trim())?)
+ }
+ }
+ })
+}
+
+fn snake(name: &str) -> String {
+ let mut s = String::new();
+ for (i, c) in name.chars().enumerate() {
+ if c.is_ascii_uppercase() {
+ if i > 0 {
+ s.push('_');
+ }
+ s.push(c.to_ascii_lowercase());
+ } else if c == '$' {
+ s.push('_');
+ } else {
+ s.push(c);
+ }
+ }
+ match s.as_str() {
+ "type" | "match" | "fn" | "ref" | "move" | "loop" | "mod" | "use" | "impl" | "trait" | "struct" | "enum"
+ | "where" | "mut" | "self" | "super" | "crate" | "box" | "gen" | "dyn" | "unsafe" | "extern" | "pub" | "as"
+ | "in" => {
+ format!("r#{s}")
+ }
+ _ => s,
+ }
+}
+
+pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {
+ let params: Vec<String> = hs
+ .params
+ .iter()
+ .map(|p| {
+ let ty = p.annotation.as_deref().and_then(rust_type).unwrap_or_else(|| "serde_json::Value".into());
+ format!("{}: {ty}", snake(&p.name))
+ })
+ .collect();
+ let ret = hs.returns.as_deref().and_then(rust_type).unwrap_or_else(|| "serde_json::Value".into());
+ format!(
+ "//! Rust port of {id} ({file}:{line}), generated by fast-anything.\n\
+ //! Replace the todo!() with a faithful, fast port. TASK.md has the original and real calls.\n\
+ //! Check it with: fast-anything verify {id}\n\n\
+ use napi::bindgen_prelude::*;\n\
+ use napi_derive::napi;\n\n\
+ #[napi(js_name = \"{js}\", catch_unwind)]\n\
+ #[allow(unused_variables)]\n\
+ pub fn {rust}({params}) -> Result<{ret}> {{\n todo!(\"port {id}\")\n}}\n",
+ id = port.id,
+ file = hs.file,
+ line = hs.line,
+ js = hs.name,
+ rust = snake(&hs.name),
+ params = params.join(", "),
+ )
+}
+
+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]\nnapi = {{ version = \"3\", features = [\"serde-json\"] }}\nnapi-derive = \"3\"\nserde_json = \"1\"\n\n\
+ [build-dependencies]\nnapi-build = \"2\"\n\n{profile}",
+ id = port.id,
+ ext = port.ext,
+ profile = backend::RELEASE_PROFILE,
+ )
+}
+
+/// A recorded value the way JavaScript would print it.
+fn js_value(v: &Value) -> String {
+ match v {
+ Value::Array(items) => format!("[{}]", items.iter().map(js_value).collect::<Vec<_>>().join(", ")),
+ Value::Object(map) => match map.iter().next() {
+ Some((tag, Value::Array(pairs))) if tag == "$object" => {
+ let inner: Vec<String> = pairs
+ .iter()
+ .filter_map(|p| p.as_array())
+ .filter(|p| p.len() == 2)
+ .map(|p| format!("{}: {}", p[0].as_str().unwrap_or("?"), js_value(&p[1])))
+ .collect();
+ format!("{{ {} }}", inner.join(", "))
+ }
+ Some((tag, x)) if tag == "$typed" => format!("{}{}", x[0].as_str().unwrap_or("TypedArray"), x[1]),
+ Some((tag, x)) if tag == "$bigint" => format!("{}n", x.as_str().unwrap_or("0")),
+ Some((tag, _)) if tag == "$undefined" => "undefined".into(),
+ Some((tag, x)) if tag == "$float" => x.as_str().unwrap_or("NaN").to_string(),
+ Some((tag, Value::Array(items))) if tag == "$set" => {
+ format!("Set {{{}}}", items.iter().map(js_value).collect::<Vec<_>>().join(", "))
+ }
+ _ => v.to_string(),
+ },
+ _ => v.to_string(),
+ }
+}
+
+fn clip(s: &str, n: usize) -> String {
+ if s.chars().count() <= n { s.to_string() } else { format!("{}…", s.chars().take(n - 1).collect::<String>()) }
+}
+
+fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
+ let Ok(text) = fs::read_to_string(path) else { return vec![] };
+ text.lines()
+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())
+ .take(n)
+ .map(|case| {
+ let args: Vec<String> =
+ case["args"].as_array().map(|a| a.iter().map(js_value).collect()).unwrap_or_default();
+ let outcome = match case.get("raises") {
+ Some(e) => format!("throws {}", e.as_str().unwrap_or("an error")),
+ None => js_value(&case["result"]),
+ };
+ format!("{} -> {}", clip(&format!("{func}({})", args.join(", ")), 110), clip(&outcome, 60))
+ })
+ .collect()
+}
+
+pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {
+ let fence = "```";
+ let lang =
+ if hs.file.ends_with(".ts") || hs.file.ends_with(".mts") || hs.file.ends_with(".cts") { "ts" } else { "js" };
+ let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
+ let notes: String = hs.warnings.iter().map(|w| format!("- Note: {w}.\n")).collect();
+ format!(
+ "# Port `{id}` to Rust\n\n\
+You're in a Rust crate (napi-rs) fast-anything generated for this: `{dir}`.\n\
+Write `{func}` in `src/lib.rs` so it behaves **exactly** like the JavaScript below, and runs fast.\n\
+Only edit files in this folder. Don't touch the JavaScript project.\n\n\
+## The original ({file}:{line})\n\n{fence}{lang}\n{source}\n{fence}\n\n\
+{helpers}## Real calls\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). 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, NaN, unicode.\n\
+- JavaScript strings are UTF-16: `.length`, indexing and `charCodeAt` count UTF-16 code units. \
+Use `s.encode_utf16()` for anything index- or length-based (bytes are fine after checking `is_ascii()`).\n\
+- JavaScript numbers are f64. Integer math is exact only up to 2^53; use `f64` unless the values are clearly small integers.\n\
+- Results are compared with a relative tolerance of 1e-9. Keep the same order of float operations.\n\
+- Where JavaScript throws, return `Err(Error::from_reason(...))`.\n\
+- Each call crosses from JavaScript into Rust: keep conversions cheap, don't clone big inputs.\n\
+- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases.\n\
+- Keep `#[napi(js_name = \"{func}\", catch_unwind)]` as it is.\n\
+{notes}\n\
+## Check\n\n\
+Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all {recorded} recorded calls against it\n\
+(`fast-anything verify {id}`).\n",
+ id = port.id,
+ dir = crate_dir.display(),
+ func = hs.name,
+ file = hs.file,
+ line = hs.line,
+ source = hs.source,
+ recorded = port.recorded,
+ seen = crate::util::thousands(port.calls_seen),
+ helpers = helpers_md(hs, helpers),
+ )
+}
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ let dir = ctx.crate_dir(port);
+ fs::create_dir_all(dir.join("src"))?;
+ fs::create_dir_all(dir.join(".cargo"))?;
+ fs::write(dir.join("Cargo.toml"), cargo_toml(port))?;
+ fs::write(dir.join("build.rs"), "fn main() {\n napi_build::setup();\n}\n")?;
+ fs::write(dir.join(".cargo/config.toml"), backend::CARGO_CONFIG)?;
+ let lib = dir.join("src/lib.rs");
+ if !lib.exists() {
+ fs::write(&lib, lib_rs(hs, port))?;
+ }
+ let task = task_md(hs, helpers, port, &dir);
+ fs::write(dir.join("TASK.md"), &task)?;
+ Ok(task)
+}
+
+/// TASK.md section listing the same-file functions the target calls, to port alongside it.
+pub fn helpers_md(hs: &Hotspot, helpers: &[Hotspot]) -> String {
+ if hs.calls.is_empty() {
+ return String::new();
+ }
+ let mut out = "## Helpers it calls\n\nPort these as private Rust functions in the same crate (they stay in JavaScript for everyone else).\n\n".to_string();
+ for name in &hs.calls {
+ match helpers.iter().find(|h| &h.name == name) {
+ Some(h) => out.push_str(&format!("```js\n{}\n```\n\n", h.source)),
+ None => out.push_str(&format!("- `{name}`: read it in {}\n", hs.file)),
+ }
+ }
+ out
+}
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ let node = ctx.runtime()?;
+ let dir = ctx.crate_dir(port);
+ let out = dir.join("verify.json");
+ let job = json!({
+ "addon": ctx.lib_dir().join(format!("{}.node", port.ext)), "js_name": port.func, "func": port.func,
+ "module_file": ctx.root.join(&port.file), "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ });
+ runner(ctx, node, "verify", job)?;
+ let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
+ v.built = true;
+ Ok(v)
+}
+
+// ------------------------------------------------------------------ the shim
+
+/// ES module or CommonJS, the way Node decides it.
+fn is_esm(root: &Path, file: &Path) -> bool {
+ match file.extension().and_then(|e| e.to_str()).unwrap_or("") {
+ "mjs" | "mts" => return true,
+ "cjs" | "cts" => return false,
+ _ => {}
+ }
+ let mut dir = file.parent();
+ while let Some(d) = dir {
+ if let Ok(text) = fs::read_to_string(d.join("package.json")) {
+ return serde_json::from_str::<Value>(&text)
+ .ok()
+ .and_then(|v| v["type"].as_str().map(|t| t == "module"))
+ .unwrap_or(false);
+ }
+ if d == root {
+ break;
+ }
+ dir = d.parent();
+ }
+ false
+}
+
+pub fn shim(port: &Port, addon_rel: &str, esm: bool) -> String {
+ let load = if esm {
+ format!("process.getBuiltinModule(\"node:module\").createRequire(import.meta.url)(\"{addon_rel}\")")
+ } else {
+ format!("require(\"{addon_rel}\")")
+ };
+ [
+ "// Uses the verified Rust port. FAST_ANYTHING_DISABLE=1 runs the JavaScript above instead.".to_string(),
+ format!("// Undo with: fast-anything disable {}", port.id),
+ "if (!process.env.FAST_ANYTHING_DISABLE) {".to_string(),
+ " try {".to_string(),
+ format!(" {f} = {load}.{f};", f = port.func),
+ " } catch {}".to_string(),
+ "}".to_string(),
+ ]
+ .join("\n")
+}
+
+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ let from = file.parent().context("module has no folder")?;
+ let mut rel = forward_slashes(&relative(from, &ctx.lib_dir().join(format!("{}.node", port.ext))));
+ if !rel.starts_with("../") {
+ rel = format!("./{rel}");
+ }
+ let block = shim(port, &rel, is_esm(&ctx.root, &file));
+ fs::write(&file, backend::append_marked(&text, "//", &port.id, &block))
+ .with_context(|| format!("writing {}", port.file))
+}
+
+pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ fs::write(&file, backend::strip_marked(&text, "//", &port.id)).with_context(|| format!("writing {}", port.file))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn maps_typescript() {
+ assert_eq!(rust_type("number").as_deref(), Some("f64"));
+ assert_eq!(rust_type("string[]").as_deref(), Some("Vec<String>"));
+ assert_eq!(rust_type("Array<number>").as_deref(), Some("Vec<f64>"));
+ assert_eq!(rust_type("readonly number[]").as_deref(), Some("Vec<f64>"));
+ assert_eq!(rust_type("number | undefined").as_deref(), Some("Option<f64>"));
+ assert_eq!(rust_type("string | null").as_deref(), Some("Option<String>"));
+ assert_eq!(rust_type("Float64Array").as_deref(), Some("Float64Array"));
+ assert_eq!(rust_type("Record<string, number>").as_deref(), Some("std::collections::HashMap<String, f64>"));
+ assert_eq!(rust_type("string | number"), None);
+ assert_eq!(rust_type("[number, number][]").as_deref(), Some("Vec<Vec<f64>>"));
+ assert_eq!(rust_type("[number, string]"), None);
+ assert_eq!(rust_type("Point"), None);
+ }
+
+ #[test]
+ fn finds_the_script() {
+ let args: Vec<String> =
+ ["--require", "x.cjs", "--no-warnings", "app.mjs", "data.txt"].map(String::from).to_vec();
+ assert_eq!(entry(&args).map(String::as_str), Some("app.mjs"));
+ assert!(is_node("node") && is_node("/usr/bin/node") && is_node("C:\\nodejs\\node.exe") && !is_node("python"));
+ assert_eq!(snake("editDistance"), "edit_distance");
+ assert_eq!(snake("type"), "r#type");
+ }
+
+ #[test]
+ fn shim_loads_the_addon() {
+ let port = Port {
+ id: "fuzzy.levenshtein".into(),
+ file: "fuzzy.mjs".into(),
+ module: "fuzzy".into(),
+ func: "levenshtein".into(),
+ ext: "fa_fuzzy_levenshtein".into(),
+ crate_dir: ".fast/ports/fuzzy.levenshtein".into(),
+ recorded: 1,
+ calls_seen: 1,
+ verify: None,
+ enabled: false,
+ lang: backend::Lang::Node,
+ owner: None,
+ };
+ 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"));
+ assert!(shim(&port, "./x.node", false).contains("levenshtein = require(\"./x.node\").levenshtein;"));
+ let original = "export function levenshtein(a, b) {\n return 0;\n}\n";
+ let on = backend::append_marked(original, "//", &port.id, &esm);
+ assert_eq!(backend::strip_marked(&on, "//", &port.id), original);
+ }
+}
diff --git a/src/node/recorder.cjs b/src/node/recorder.cjs
new file mode 100644
index 0000000..2fc0ecc
--- /dev/null
+++ b/src/node/recorder.cjs
@@ -0,0 +1,78 @@
+// fast-anything call recorder, preloaded with "node --require". Not meant to be used by hand.
+"use strict";
+const fs = require("node:fs");
+
+const out = process.env.FAST_ANYTHING_RECORD_OUT;
+const meta = process.env.FAST_ANYTHING_RECORD_META;
+const limit = Number(process.env.FAST_ANYTHING_RECORD_LIMIT || 500);
+const kept = [];
+const unsupported = new Set();
+let calls = 0;
+let skipped = 0;
+let seed = 0xfa57;
+const rand = (n) => {
+ seed = (Math.imul(seed, 1103515245) + 12345) >>> 0;
+ return seed % n;
+};
+
+function enc(v) {
+ if (v === null || typeof v === "string" || typeof v === "boolean") return v;
+ if (typeof v === "number") return Number.isFinite(v) ? (Object.is(v, -0) ? { $float: "-0" } : v) : { $float: String(v) };
+ if (v === undefined) return { $undefined: 0 };
+ if (typeof v === "bigint") return { $bigint: v.toString() };
+ if (Array.isArray(v)) return v.map(enc);
+ if (ArrayBuffer.isView(v) && !(v instanceof DataView))
+ return { $typed: [v.constructor.name, Array.from(v, (x) => (typeof x === "bigint" ? x.toString() : x))] };
+ if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k), enc(x)]) };
+ if (v instanceof Set) return { $set: [...v].map(enc) };
+ if (typeof v === "object") {
+ const proto = Object.getPrototypeOf(v);
+ if (proto === Object.prototype || proto === null) return { $object: Object.entries(v).map(([k, x]) => [k, enc(x)]) };
+ }
+ throw new Error(typeof v === "object" ? (v.constructor?.name ?? "object") : typeof v);
+}
+
+function store(slot, c) {
+ if (kept.length < limit) kept.push(c);
+ else kept[slot % limit] = c;
+}
+
+globalThis.__fastAnythingWrap = (fn) =>
+ function (...args) {
+ calls++;
+ const slot = kept.length < limit ? kept.length : rand(calls);
+ let c = null;
+ if (slot < limit) {
+ try {
+ c = { args: args.map(enc) };
+ } catch (e) {
+ skipped++;
+ unsupported.add(e.message);
+ }
+ }
+ let result;
+ try {
+ result = fn.apply(this, args);
+ } catch (e) {
+ if (c) {
+ c.raises = (e && e.name) || "Error";
+ store(slot, c);
+ }
+ throw e;
+ }
+ if (c) {
+ try {
+ c.result = enc(result);
+ store(slot, c);
+ } catch (e) {
+ skipped++;
+ unsupported.add(e.message);
+ }
+ }
+ return result;
+ };
+
+process.on("exit", () => {
+ fs.writeFileSync(out, kept.map((c) => JSON.stringify(c)).join("\n") + (kept.length ? "\n" : ""));
+ fs.writeFileSync(meta, JSON.stringify({ calls, kept: kept.length, skipped, unsupported: [...unsupported] }));
+});
diff --git a/src/node/runner.mjs b/src/node/runner.mjs
new file mode 100644
index 0000000..1c8eea9
--- /dev/null
+++ b/src/node/runner.mjs
@@ -0,0 +1,470 @@
+// Node side of fast-anything. The CLI copies this file to <project>/.fast/runner.mjs and runs
+// node runner.mjs <mode> <job.json>
+// Modes: profile (analyse a V8 .cpuprofile), verify. Not meant to be run by hand.
+import { readFileSync, writeFileSync, readdirSync, statSync } from "node:fs";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SKIP_DIRS = new Set([".fast", ".git", "node_modules"]);
+const IO =
+ /\b(console|fs|process|fetch|require|XMLHttpRequest|document|window|localStorage|sessionStorage|setTimeout|setInterval|setImmediate|queueMicrotask|Bun|Deno)\b|\bimport\s*\(/g;
+const NONDET = /\bMath\.random\b|\bDate\.now\b|\bnew\s+Date\b|\bperformance\.now\b|\bcrypto\.\w+/g;
+const IDENT = "[A-Za-z_$][\\w$]*";
+const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+// ------------------------------------------------------------------ source scanning
+
+/** The source with string contents and comments blanked out (same length, same lines). */
+function codeOnly(src) {
+ const out = src.split("");
+ const blank = (a, b) => {
+ for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
+ };
+ let i = 0;
+ while (i < src.length) {
+ const c = src[i];
+ if (c === "/" && src[i + 1] === "/") {
+ const end = src.indexOf("\n", i);
+ blank(i, end < 0 ? src.length : end);
+ i = end < 0 ? src.length : end;
+ } else if (c === "/" && src[i + 1] === "*") {
+ const end = src.indexOf("*/", i + 2);
+ blank(i, end < 0 ? src.length : end + 2);
+ i = end < 0 ? src.length : end + 2;
+ } else if (c === '"' || c === "'" || c === "`") {
+ let j = i + 1;
+ while (j < src.length && src[j] !== c) j += src[j] === "\\" ? 2 : 1;
+ blank(i + 1, j);
+ i = j + 1;
+ } else i++;
+ }
+ return out.join("");
+}
+
+function matching(code, open) {
+ const close = { "(": ")", "{": "}", "[": "]" }[code[open]];
+ let depth = 0;
+ for (let i = open; i < code.length; i++) {
+ if (code[i] === code[open]) depth++;
+ else if (code[i] === close && --depth === 0) return i;
+ }
+ return -1;
+}
+
+function splitTop(s) {
+ const parts = [];
+ let depth = 0;
+ let cur = "";
+ for (const c of s) {
+ if ("([{<".includes(c)) depth++;
+ if (")]}>".includes(c)) depth--;
+ if (c === "," && depth === 0) {
+ parts.push(cur);
+ cur = "";
+ } else cur += c;
+ }
+ if (cur.trim()) parts.push(cur);
+ return parts.map((p) => p.trim()).filter(Boolean);
+}
+
+function defaultAt(s) {
+ let depth = 0;
+ for (let i = 0; i < s.length; i++) {
+ if ("([{<".includes(s[i])) depth++;
+ else if (")]}>".includes(s[i]) && s[i - 1] !== "=") depth--;
+ else if (s[i] === "=" && depth === 0 && s[i + 1] !== ">" && s[i + 1] !== "=") return i;
+ }
+ return -1;
+}
+
+function parseParams(text) {
+ return splitTop(text).map((p) => {
+ let name = p;
+ let annotation = null;
+ const eq = defaultAt(p);
+ if (eq >= 0) name = p.slice(0, eq).trim();
+ const rest = name.startsWith("...");
+ if (rest) name = name.slice(3);
+ const colon = name.indexOf(":");
+ if (colon >= 0) {
+ annotation = name.slice(colon + 1).trim();
+ name = name.slice(0, colon).trim();
+ }
+ const optional = name.endsWith("?") || eq >= 0;
+ name = name.replace(/\?$/, "").trim();
+ if (optional && annotation) annotation += " | undefined";
+ return { name, annotation, rest, destructured: /^[[{]/.test(name) };
+ });
+}
+
+function topLevelFunctions(src) {
+ const re = new RegExp(
+ "^(?:export\\s+)?(?:default\\s+)?(?:async\\s+)?function\\s*\\*?\\s*(" + IDENT + ")" +
+ "|^(?:export\\s+)?(?:let|var|const)\\s+(" + IDENT + ")\\s*(?::[^=]+)?=\\s*(?:async\\s*)?(?:function\\b|\\(|" + IDENT + "\\s*=>)",
+ "gm",
+ );
+ return new Set([...src.matchAll(re)].map((m) => m[1] || m[2]));
+}
+
+const parsed = new Map();
+
+function describe(file, line0, name, entry, root) {
+ if (!parsed.has(file)) {
+ try {
+ const src = readFileSync(file, "utf8");
+ parsed.set(file, { src, code: codeOnly(src), top: topLevelFunctions(src) });
+ } catch {
+ parsed.set(file, null);
+ }
+ }
+ const f = parsed.get(file);
+ if (!f) return null;
+ const { src, code, top } = f;
+ const lines = code.split("\n");
+ const n = esc(name);
+ const patterns = [
+ ["function", new RegExp("^(\\s*)(export\\s+)?(default\\s+)?(async\\s+)?function\\s*(\\*)?\\s*" + n + "\\s*(<[^(]*>)?\\s*\\(")],
+ ["binding", new RegExp("^(\\s*)(export\\s+)?(const|let|var)\\s+" + n + "\\s*(:[^=]+)?=\\s*(async\\s*)?(function\\s*\\*?\\s*[\\w$]*\\s*\\(|\\()")],
+ ["method", new RegExp("^(\\s*)(static\\s+)?(async\\s+)?(\\*)?\\s*" + n + "\\s*\\(")],
+ ];
+ let hit = null;
+ for (const l of [line0, line0 - 1, line0 - 2, line0 + 1]) {
+ if (l < 0 || l >= lines.length) continue;
+ for (const [kind, re] of patterns) {
+ const m = lines[l].match(re);
+ if (m) {
+ hit = { kind, m, l };
+ break;
+ }
+ }
+ if (hit) break;
+ }
+ if (!hit) return null;
+ const { kind, m, l } = hit;
+ const lineStart = lines.slice(0, l).reduce((a, s) => a + s.length + 1, 0);
+ const open = lineStart + m[0].length - 1;
+ const close = matching(code, open);
+ if (close < 0) return null;
+
+ const blockers = [];
+ const warnings = [];
+ let factor = 1;
+ const indent = m[1].length;
+ const rel = path.relative(root, file);
+ const isEntry = entry && path.resolve(entry) === path.resolve(file);
+ const module = isEntry ? "__main__" : rel.replace(/\.[cm]?[jt]sx?$/, "").split(path.sep).join(".");
+ if (isEntry) blockers.push("lives in the entry script, move it into a module to port it");
+ if (kind === "method" || indent > 0) blockers.push("method or nested function (top-level functions only for now)");
+ if (kind === "function" && m[4]) blockers.push("async");
+ if (kind === "function" && m[5]) blockers.push("generator (function*)");
+ if (kind === "binding" && m[5]) blockers.push("async");
+ if (kind === "binding" && m[3] === "const") blockers.push("declared with const, write it as function " + name + "(...) to port it");
+
+ const after = close + 1;
+ const sig = src.slice(after, after + 400).match(/^\s*:\s*([^{=]+?)\s*(\{|=>)/);
+ const returns = sig ? sig[1].trim() : null;
+ let bodyStart = code.indexOf("{", after);
+ const between = code.slice(after, bodyStart < 0 ? code.length : bodyStart + 1);
+ let bodyEnd;
+ if (bodyStart >= 0 && !/=>\s*[^\s{]/.test(between)) bodyEnd = matching(code, bodyStart);
+ else {
+ bodyStart = after;
+ const semi = code.indexOf(";", after);
+ const nl = code.indexOf("\n", after);
+ bodyEnd = Math.min(semi < 0 ? code.length : semi, nl < 0 ? code.length : nl);
+ }
+ if (bodyEnd < 0) return null;
+ const body = code.slice(bodyStart, bodyEnd + 1);
+
+ const io = new Set([...body.matchAll(IO)].map((x) => x[0]));
+ const nondet = new Set([...body.matchAll(NONDET)].map((x) => x[0]));
+ if (/\byield\b/.test(body) && !blockers.some((b) => b.startsWith("generator"))) blockers.push("generator (yield)");
+ if (/\bawait\b/.test(body) && !blockers.includes("async")) blockers.push("async");
+ if (/\bthis\b/.test(body)) blockers.push("uses this");
+ if (io.size) blockers.push("does I/O: " + [...io].slice(0, 3).join(", "));
+ if (nondet.size) blockers.push("not deterministic: " + [...nondet].slice(0, 3).join(", "));
+ const helpers = [...top].filter((h) => h !== name && new RegExp("\\b" + esc(h) + "\\s*\\(").test(body));
+ if (helpers.length) warnings.push("calls " + helpers.slice(0, 3).join(", ") + ", they get ported together with it");
+
+ const params = parseParams(src.slice(open + 1, close));
+ if (params.some((p) => p.rest)) {
+ warnings.push("takes ...rest parameters");
+ factor *= 0.7;
+ }
+ if (params.some((p) => p.destructured)) {
+ warnings.push("destructures its parameters");
+ factor *= 0.8;
+ }
+ if (returns === null || params.some((p) => !p.annotation)) {
+ warnings.push("no TypeScript types, types are inferred from recorded calls");
+ factor *= 0.9;
+ }
+ return {
+ qualname: name,
+ module,
+ kind: kind === "method" || indent > 0 ? "method" : "function",
+ end_line: src.slice(0, bodyEnd + 1).split("\n").length,
+ params: params.map(({ name, annotation }) => ({ name, annotation })),
+ returns,
+ blockers,
+ warnings,
+ portability: blockers.length ? 0 : factor,
+ calls: helpers,
+ source: src.slice(lineStart, bodyEnd + 1),
+ };
+}
+
+function projectRelative(root, file) {
+ const rel = path.relative(root, file);
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
+ if (rel.split(path.sep).slice(0, -1).some((p) => SKIP_DIRS.has(p))) return null;
+ return rel;
+}
+
+// ------------------------------------------------------------------ profile
+
+function profile(job) {
+ const names = readdirSync(job.dir).filter((f) => f.endsWith(".cpuprofile"));
+ if (!names.length) throw new Error("node wrote no .cpuprofile");
+ names.sort((a, b) => statSync(path.join(job.dir, b)).size - statSync(path.join(job.dir, a)).size);
+ const prof = JSON.parse(readFileSync(path.join(job.dir, names[0]), "utf8"));
+
+ const byId = new Map(prof.nodes.map((n) => [n.id, n]));
+ const parent = new Map();
+ for (const n of prof.nodes) for (const c of n.children || []) parent.set(c, n.id);
+ const selfUs = new Map();
+ prof.samples.forEach((id, i) => selfUs.set(id, (selfUs.get(id) || 0) + (prof.timeDeltas[i] || 0)));
+ const total = (prof.endTime - prof.startTime) / 1e6;
+
+ const key = (n) => `${n.callFrame.url}:${n.callFrame.lineNumber}:${n.callFrame.columnNumber}:${n.callFrame.functionName}`;
+ const funcs = new Map();
+ for (const n of prof.nodes) if (!funcs.has(key(n))) funcs.set(key(n), { frame: n.callFrame, self: 0, cum: 0 });
+ for (const [id, us] of selfUs) {
+ let node = byId.get(id);
+ funcs.get(key(node)).self += us;
+ const seen = new Set();
+ while (node) {
+ const k = key(node);
+ if (!seen.has(k)) {
+ seen.add(k);
+ funcs.get(k).cum += us;
+ }
+ node = byId.get(parent.get(node.id));
+ }
+ }
+
+ const rows = [];
+ for (const f of funcs.values()) {
+ const { url, functionName, lineNumber } = f.frame;
+ if (!functionName || !url.startsWith("file:")) continue;
+ const file = fileURLToPath(url);
+ const rel = projectRelative(job.root, file);
+ if (rel) rows.push({ file, rel, line0: lineNumber, name: functionName, self: f.self / 1e6, cum: f.cum / 1e6 });
+ }
+ rows.sort((a, b) => b.cum - a.cum);
+ const functions = [];
+ for (const r of rows.slice(0, 40)) {
+ const info = describe(r.file, r.line0, r.name, job.entry, job.root);
+ if (info)
+ functions.push({ ...info, file: r.rel.split(path.sep).join("/"), line: r.line0 + 1, name: r.name, ncalls: 0, tottime: r.self, cumtime: r.cum });
+ }
+ writeFileSync(job.out, JSON.stringify({ wall: total, base: ".", functions }));
+}
+
+// ------------------------------------------------------------------ verify
+
+function dec(v) {
+ if (Array.isArray(v)) return v.map(dec);
+ if (v === null || typeof v !== "object") return v;
+ const [[tag, x]] = Object.entries(v);
+ switch (tag) {
+ case "$float": return Number(x);
+ case "$undefined": return undefined;
+ case "$bigint": return BigInt(x);
+ case "$typed": return new globalThis[x[0]](x[1].map((e) => (x[0].startsWith("Big") ? BigInt(e) : e)));
+ case "$map": return new Map(x.map(([k, e]) => [dec(k), dec(e)]));
+ case "$set": return new Set(x.map(dec));
+ case "$object": return Object.fromEntries(x.map(([k, e]) => [k, dec(e)]));
+ }
+ throw new Error("unknown tag " + tag);
+}
+
+function same(a, b) {
+ if (a == null && b == null) return true;
+ if (typeof a === "number" && typeof b === "number") {
+ if (Number.isNaN(a) || Number.isNaN(b)) return Number.isNaN(a) && Number.isNaN(b);
+ return a === b || Math.abs(a - b) <= Math.max(1e-12, 1e-9 * Math.max(Math.abs(a), Math.abs(b)));
+ }
+ if (typeof a === "bigint" || typeof b === "bigint") {
+ try {
+ return BigInt(a) === BigInt(b);
+ } catch {
+ return false;
+ }
+ }
+ const seq = (x) => Array.isArray(x) || (ArrayBuffer.isView(x) && !(x instanceof DataView));
+ if (seq(a) && seq(b)) return a.length === b.length && Array.from(a).every((x, i) => same(x, b[i]));
+ if (a instanceof Set && b instanceof Set) return a.size === b.size && [...a].every((x) => b.has(x));
+ if (a instanceof Map && b instanceof Map) return a.size === b.size && [...a].every(([k, x]) => b.has(k) && same(x, b.get(k)));
+ if (a && b && typeof a === "object" && typeof b === "object") {
+ const ka = Object.keys(a);
+ return ka.length === Object.keys(b).length && ka.every((k) => Object.hasOwn(b, k) && same(a[k], b[k]));
+ }
+ return a === b;
+}
+
+function show(v, limit = 160) {
+ let s;
+ try {
+ s = v === undefined ? "undefined" : JSON.stringify(v, (_, x) => (typeof x === "bigint" ? x + "n" : x)) ?? String(v);
+ } catch {
+ s = String(v);
+ }
+ return s.length <= limit ? s : s.slice(0, limit - 1) + "…";
+}
+
+const SLICE_LENGTHS = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55];
+
+/** Smaller versions of an array/string/typed-array argument: empty, tiny, and random slices. */
+function variants(value, rand) {
+ const sliceable = typeof value === "string" || Array.isArray(value) || (ArrayBuffer.isView(value) && !(value instanceof DataView));
+ if (!sliceable || value.length < 2) return [];
+ return SLICE_LENGTHS.filter((len) => len < value.length).flatMap((len) =>
+ Array.from({ length: len < 2 ? 1 : 3 }, () => {
+ const start = Math.floor(rand() * (value.length - len + 1));
+ return value.slice(start, start + len);
+ }),
+ );
+}
+
+/** Extra test cases: recorded calls with smaller inputs, answered by the original itself. */
+function derive(original, cases, budget, limit) {
+ let seed = 0xfa57;
+ const rand = () => ((seed = (Math.imul(seed, 1103515245) + 12345) >>> 0) / 4294967296);
+ const derived = [];
+ const seen = new Set();
+ const start = performance.now();
+ for (const c of cases) {
+ if ("raises" in c) continue;
+ const args = dec(c.args);
+ for (let i = 0; i < args.length; i++) {
+ for (const smaller of variants(args[i], rand)) {
+ if (derived.length >= limit || (performance.now() - start) / 1000 > budget) return derived;
+ const next = args.slice();
+ next[i] = smaller;
+ let encoded;
+ try {
+ encoded = { args: next.map(enc) };
+ const key = JSON.stringify(encoded);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ encoded.result = enc(original(...structuredClone(next)));
+ } catch {
+ continue; // outside the function's domain: not a fair test
+ }
+ encoded.derived = true;
+ derived.push(encoded);
+ }
+ }
+ }
+ return derived;
+}
+
+function enc(v) {
+ if (v === null || typeof v === "string" || typeof v === "boolean") return v;
+ if (typeof v === "number") return Number.isFinite(v) ? (Object.is(v, -0) ? { $float: "-0" } : v) : { $float: String(v) };
+ if (v === undefined) return { $undefined: 0 };
+ if (typeof v === "bigint") return { $bigint: v.toString() };
+ if (Array.isArray(v)) return v.map(enc);
+ if (ArrayBuffer.isView(v) && !(v instanceof DataView))
+ return { $typed: [v.constructor.name, Array.from(v, (x) => (typeof x === "bigint" ? x.toString() : x))] };
+ if (v instanceof Map) return { $map: [...v].map(([k, x]) => [enc(k), enc(x)]) };
+ if (v instanceof Set) return { $set: [...v].map(enc) };
+ if (typeof v === "object") {
+ const proto = Object.getPrototypeOf(v);
+ if (proto === Object.prototype || proto === null) return { $object: Object.entries(v).map(([k, x]) => [k, enc(x)]) };
+ }
+ throw new Error("unsupported");
+}
+
+function bestPass(fn, calls, budget) {
+ let best = Infinity;
+ let spent = 0;
+ let passes = 0;
+ while (passes < 3 || (spent < budget && passes < 2000)) {
+ const t = performance.now();
+ for (const args of calls) {
+ try {
+ fn(...args);
+ } catch {}
+ }
+ const took = (performance.now() - t) / 1000;
+ best = Math.min(best, took);
+ spent += took;
+ passes++;
+ }
+ return best;
+}
+
+async function verify(job) {
+ process.env.FAST_ANYTHING_DISABLE = "1";
+ const fast = createRequire(import.meta.url)(job.addon)[job.js_name];
+ if (typeof fast !== "function") throw new Error(job.addon + " doesn't export " + job.js_name);
+ let original = null;
+ try {
+ const mod = await import(pathToFileURL(job.module_file).href);
+ original = mod[job.func] ?? mod.default?.[job.func] ?? null;
+ } catch {}
+
+ const cases = readFileSync(job.cases, "utf8").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
+ const recorded = cases.length;
+ const derived = typeof original === "function" ? derive(original, cases, job.derive_budget ?? 3, job.derive_limit ?? 200) : [];
+ cases.push(...derived);
+ const report = { total: cases.length, derived: derived.length, passed: 0, failed: 0, failures: [] };
+ const calls = [];
+ cases.forEach((c, i) => {
+ const args = dec(c.args);
+ calls.push(args);
+ let got;
+ let err = null;
+ try {
+ got = fast(...args);
+ } catch (e) {
+ err = e;
+ }
+ let ok;
+ let expected;
+ if ("raises" in c) [ok, expected] = [err !== null, "throws " + c.raises];
+ else {
+ const want = dec(c.result);
+ [ok, expected] = [err === null && same(want, got), show(want)];
+ }
+ if (ok) {
+ report.passed++;
+ return;
+ }
+ report.failed++;
+ if (report.failures.length < 8)
+ report.failures.push({
+ case: i,
+ call: (c.derived ? "(derived) " : "") + job.func + "(" + args.map((a) => show(a, 80)).join(", ") + ")",
+ expected,
+ got: err === null ? show(got) : "threw " + (err?.name ?? "Error") + ": " + show(String(err?.message ?? err), 200),
+ });
+ });
+
+ if (cases.length && report.failed === 0 && typeof original === "function") {
+ calls.length = recorded;
+ const js = bestPass(original, calls, job.budget ?? 0.5);
+ const rs = bestPass(fast, calls, job.budget ?? 0.5);
+ report.micro = { original_ns: (js / calls.length) * 1e9, rust_ns: (rs / calls.length) * 1e9, speedup: rs > 0 ? js / rs : 0 };
+ }
+ writeFileSync(job.out, JSON.stringify(report));
+}
+
+const [mode, jobPath] = process.argv.slice(2);
+const job = JSON.parse(readFileSync(jobPath, "utf8"));
+if (mode === "profile") profile(job);
+else if (mode === "verify") await verify(job);
+else throw new Error("unknown mode " + mode);
diff --git a/src/pipeline.rs b/src/pipeline.rs
new file mode 100644
index 0000000..7e9f229
--- /dev/null
+++ b/src/pipeline.rs
@@ -0,0 +1,316 @@
+//! The steps (scan, port, verify, enable, bench, report) shared by the CLI and the MCP server.
+
+use crate::backend::{self, Lang};
+use crate::bench::{self, BenchResult};
+use crate::hotspot::{self, Hotspot};
+use crate::report::{self, ReportOut};
+use crate::state::{Ctx, Port, Verify};
+use crate::{agent, show, ui, util};
+use anyhow::{Context, Result, bail, ensure};
+use serde::Serialize;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+#[derive(Serialize)]
+pub struct ScanOut {
+ pub command: Vec<String>,
+ pub wall: f64,
+ pub hotspots: Vec<Hotspot>,
+}
+
+pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {
+ ensure!(
+ !command.is_empty(),
+ "put the command that runs your app after --, e.g. fast-anything scan -- python app.py"
+ );
+ let mut ctx = Ctx::open(root)?;
+ let lang = Lang::detect(&command[0])?;
+ let exe = lang.resolve(&command[0], &ctx.root)?;
+ ui::step(format!("profiling {}", ui::bold(command.join(" "))));
+ let profile = lang.profile(&ctx, &exe, &command[1..])?;
+ let hotspots = hotspot::rank(profile.functions, profile.wall);
+ ctx.state.command = command.clone();
+ ctx.state.lang = lang;
+ ctx.state.runtime = Some(exe);
+ ctx.state.base = profile.base;
+ ctx.state.wall = profile.wall;
+ ctx.state.hotspots = hotspots.clone();
+ ctx.save()?;
+ Ok(ScanOut { command, wall: profile.wall, hotspots })
+}
+
+fn pick<'a>(hotspots: &'a [Hotspot], id: Option<&str>) -> Result<&'a Hotspot> {
+ let Some(id) = id else {
+ return hotspots
+ .iter()
+ .find(|h| h.worth_it())
+ .context("no function worth porting in the last scan (see fast-anything status for why)");
+ };
+ if let Some(h) = hotspots.iter().find(|h| h.id == id) {
+ return Ok(h);
+ }
+ let hits: Vec<&Hotspot> = hotspots.iter().filter(|h| h.name == id || h.qualname == id).collect();
+ match hits.as_slice() {
+ [one] => Ok(one),
+ [] => bail!("{id} wasn't in the last scan; run fast-anything scan -- ... again, or check the name"),
+ many => bail!("{id} is ambiguous: {}", many.iter().map(|h| h.id.as_str()).collect::<Vec<_>>().join(", ")),
+ }
+}
+
+#[derive(Serialize)]
+pub struct PortOut {
+ pub id: String,
+ pub crate_dir: PathBuf,
+ pub lib_rs: PathBuf,
+ pub task_md: PathBuf,
+ pub recorded: usize,
+ pub calls_seen: u64,
+ pub skipped: usize,
+ pub task: String,
+}
+
+pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {
+ let mut ctx = Ctx::open(root)?;
+ let exe = ctx.runtime()?.to_string();
+ let lang = ctx.state.lang;
+ let hs = pick(&ctx.state.hotspots, id)?.clone();
+ if !hs.portable() {
+ bail!("{} can't be ported yet: {}", hs.id, hs.blockers.join("; "));
+ }
+ let module = hs.module.clone().unwrap_or_default();
+ let crate_rel = format!(".fast/ports/{}", hs.id.replace([':', '/', '\\'], "."));
+ let dir = ctx.root.join(&crate_rel);
+ fs::create_dir_all(&dir)?;
+
+ ui::step(format!("running the app again to record real calls to {}", ui::bold(&hs.id)));
+ let app_args = ctx.state.command[1..].to_vec();
+ let rec = lang.record(&ctx, &exe, &app_args, &hs, &dir.join("recordings.jsonl"), samples.max(1))?;
+ if rec.kept == 0 {
+ let types =
+ if rec.unsupported.is_empty() { String::new() } else { format!(" (got: {})", rec.unsupported.join(", ")) };
+ bail!(
+ "recorded no usable calls to {} out of {}. Arguments and results must be plain data: numbers, strings, bytes, lists, tuples, dicts, sets{types}",
+ hs.id,
+ rec.calls
+ );
+ }
+ let enabled = ctx.state.ports.get(&hs.id).is_some_and(|p| p.enabled);
+ let port = Port {
+ id: hs.id.clone(),
+ file: hs.file.clone(),
+ module,
+ func: hs.name.clone(),
+ ext: format!("fa_{}", util::slug(&hs.id)),
+ crate_dir: crate_rel,
+ recorded: rec.kept,
+ calls_seen: rec.calls,
+ verify: None,
+ enabled,
+ lang,
+ owner: hs.owner.clone(),
+ };
+ let helpers: Vec<Hotspot> = hs
+ .calls
+ .iter()
+ .filter_map(|name| ctx.state.hotspots.iter().find(|h| h.file == hs.file && &h.name == name))
+ .cloned()
+ .collect();
+ let task = lang.scaffold(&ctx, &hs, &helpers, &port)?;
+ ctx.state.ports.insert(port.id.clone(), port);
+ ctx.save()?;
+ Ok(PortOut {
+ id: hs.id,
+ lib_rs: dir.join("src").join(if lang == Lang::Ruby { "port.rs" } else { "lib.rs" }),
+ task_md: dir.join("TASK.md"),
+ crate_dir: dir,
+ recorded: rec.kept,
+ calls_seen: rec.calls,
+ skipped: rec.skipped,
+ task,
+ })
+}
+
+pub fn verify(root: &Path, id: Option<&str>) -> Result<(String, Verify)> {
+ let mut ctx = Ctx::open(root)?;
+ let id = ctx.resolve_port(id)?;
+ let port = ctx.state.ports[&id].clone();
+ ui::step(format!("building {} (release)", ui::bold(&port.ext)));
+ let v = match backend::build(&ctx, &port)? {
+ Err(log) => Verify { built: false, build_log: Some(log), ..Verify::default() },
+ Ok(_) => {
+ ui::step(format!(
+ "replaying {} recorded call{} against the Rust port",
+ port.recorded,
+ if port.recorded == 1 { "" } else { "s" }
+ ));
+ port.lang.verify(&ctx, &port)?
+ }
+ };
+ let mut v = v;
+ v.lang = port.lang;
+ if !v.ok() && port.enabled {
+ port.lang.disable(&ctx, &port)?;
+ 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"));
+ }
+ if let Some(p) = ctx.state.ports.get_mut(&id) {
+ p.verify = Some(v.clone());
+ }
+ ctx.save()?;
+ Ok((id, v))
+}
+
+pub fn enable(root: &Path, id: Option<&str>, force: bool) -> Result<String> {
+ let mut ctx = Ctx::open(root)?;
+ let id = ctx.resolve_port(id)?;
+ let port = ctx.state.ports[&id].clone();
+ let verified = port.verify.as_ref().is_some_and(Verify::ok);
+ if !verified && !force {
+ bail!("{id} hasn't passed verify yet: run fast-anything verify {id} (or --force)");
+ }
+ port.lang.enable(&ctx, &port)?;
+ if let Some(p) = ctx.state.ports.get_mut(&id) {
+ p.enabled = true;
+ }
+ ctx.save()?;
+ Ok(id)
+}
+
+pub fn disable(root: &Path, id: Option<&str>) -> Result<String> {
+ let mut ctx = Ctx::open(root)?;
+ let id = ctx.resolve_port(id)?;
+ let port = &ctx.state.ports[&id];
+ port.lang.disable(&ctx, port)?;
+ if let Some(p) = ctx.state.ports.get_mut(&id) {
+ p.enabled = false;
+ }
+ ctx.save()?;
+ Ok(id)
+}
+
+pub fn build_all(root: &Path) -> Result<()> {
+ let ctx = Ctx::open(root)?;
+ ensure!(!ctx.state.ports.is_empty(), "nothing ported yet");
+ let mut failed = 0;
+ for port in ctx.state.ports.values() {
+ ui::step(format!("building {}", ui::bold(&port.id)));
+ match backend::build(&ctx, port)? {
+ Ok(path) => ui::ok(format!("{}", path.display())),
+ Err(log) => {
+ failed += 1;
+ ui::error(format!("{} doesn't compile:\n{log}", port.id));
+ }
+ }
+ }
+ ensure!(failed == 0, "{failed} port(s) didn't build");
+ Ok(())
+}
+
+pub fn bench(root: &Path, runs: usize) -> Result<BenchResult> {
+ let mut ctx = Ctx::open(root)?;
+ let result = bench::run(&ctx, runs.max(1))?;
+ ctx.state.bench = Some(result.clone());
+ ctx.save()?;
+ Ok(result)
+}
+
+pub fn report(root: &Path) -> Result<ReportOut> {
+ report::write(&Ctx::open(root)?)
+}
+
+/// What the agent gets told after a failed attempt.
+pub fn feedback(v: &Verify) -> String {
+ let mut out = String::from("\n\n## Your last attempt failed\n\n");
+ if let Some(log) = &v.build_log {
+ out.push_str("It doesn't compile:\n\n```\n");
+ out.push_str(log);
+ out.push_str("\n```\n");
+ } else {
+ out.push_str(&format!("{} of {} recorded calls came out different:\n\n", v.failed, v.total));
+ for f in &v.failures {
+ 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
+}
+
+pub fn agent_port(root: &Path, id: &str, agent_spec: &str, attempts: usize) -> Result<Verify> {
+ let attempts = attempts.max(1);
+ let mut last: Option<Verify> = None;
+ for attempt in 1..=attempts {
+ let ctx = Ctx::open(root)?;
+ let port = ctx.state.ports.get(id).with_context(|| format!("{id} isn't ported"))?.clone();
+ let dir = ctx.crate_dir(&port);
+ let mut prompt = fs::read_to_string(dir.join("TASK.md")).context("reading TASK.md")?;
+ if let Some(v) = &last {
+ prompt.push_str(&feedback(v));
+ }
+ ui::step(format!("{} is writing the Rust port (attempt {attempt}/{attempts})", ui::bold(agent_spec)));
+ agent::run(agent_spec, &dir, &prompt, &dir.join("agent.log"))?;
+ let (_, v) = verify(root, Some(id))?;
+ show::verify(id, &v);
+ if v.ok() {
+ return Ok(v);
+ }
+ last = Some(v);
+ }
+ Ok(last.unwrap_or_default())
+}
+
+pub fn go(
+ root: &Path,
+ command: Vec<String>,
+ agent_spec: Option<&str>,
+ top: usize,
+ attempts: usize,
+ runs: usize,
+ samples: usize,
+) -> Result<()> {
+ let scanned = scan(root, command)?;
+ show::scan(&scanned);
+ let picks: Vec<String> =
+ scanned.hotspots.iter().filter(|h| h.worth_it()).take(top.max(1)).map(|h| h.id.clone()).collect();
+ ensure!(
+ !picks.is_empty(),
+ "nothing worth porting: no portable function takes {}% or more of the run",
+ hotspot::WORTH_IT * 100.0
+ );
+
+ let Some(agent_spec) = agent_spec else {
+ for id in &picks {
+ show::port(&port(root, Some(id), samples)?, false);
+ }
+ ui::line("");
+ ui::line(format!(
+ " Now write the Rust: hand each TASK.md to your coding agent (or pass {}), then:",
+ ui::bold("--agent claude")
+ ));
+ for id in &picks {
+ show::next(&format!("fast-anything verify {id} && fast-anything enable {id}"));
+ }
+ show::next("fast-anything bench");
+ return Ok(());
+ };
+
+ let mut enabled = 0;
+ for id in &picks {
+ show::port(&port(root, Some(id), samples)?, false);
+ let v = agent_port(root, id, agent_spec, attempts)?;
+ if v.ok() {
+ enable(root, Some(id), false)?;
+ ui::ok(format!("{} now runs in Rust", ui::bold(id)));
+ enabled += 1;
+ } else {
+ ui::warn(format!(
+ "{id}: not right after {attempts} attempts; fix src/lib.rs by hand (see TASK.md), then fast-anything verify {id}"
+ ));
+ }
+ }
+ ensure!(enabled > 0, "no port passed verification");
+ show::bench(&bench(root, runs)?);
+ show::report(&report(root)?);
+ Ok(())
+}
diff --git a/src/python.rs b/src/python.rs
new file mode 100644
index 0000000..7e660c6
--- /dev/null
+++ b/src/python.rs
@@ -0,0 +1,543 @@
+//! Python backend: profile with cProfile, record real calls, scaffold a PyO3 crate, build it,
+//! replay the recordings against it, and swap it in with a small reversible shim.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::Hotspot;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{combined, forward_slashes, output, relative, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde_json::{Value, json};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, Stdio};
+
+const RUNNER: &str = include_str!("python/runner.py");
+const PYO3: &str = "0.30";
+pub const DISABLE_ENV: &str = "FAST_ANYTHING_DISABLE";
+
+pub fn is_python(program: &str) -> bool {
+ let stem = Path::new(program).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase();
+ stem == "py" || stem.starts_with("python") || stem.starts_with("pypy")
+}
+
+/// The absolute interpreter path behind python, python3, py, .venv/bin/python, ...
+pub fn resolve(program: &str, root: &Path) -> Result<String> {
+ if !is_python(program) {
+ bail!(
+ "fast-anything v0.1 speaks Python. Start the command with python, e.g.\n fast-anything scan -- python app.py\n (Node/TypeScript is next on the roadmap)"
+ );
+ }
+ let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };
+ let out = output(
+ Command::new(&prog)
+ .args(["-c", "import sys; print(sys.executable); print(*sys.version_info[:2])"])
+ .current_dir(root),
+ "python",
+ )?;
+ ensure!(out.status.success(), "{program} failed:\n{}", tail(&combined(&out), 5));
+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
+ let mut lines = text.lines();
+ let exe = lines.next().unwrap_or_default().trim().to_string();
+ let version: Vec<u32> =
+ lines.next().unwrap_or_default().split_whitespace().filter_map(|s| s.parse().ok()).collect();
+ ensure!(!exe.is_empty(), "couldn't find the interpreter behind {program}");
+ ensure!(version.as_slice() >= &[3, 10][..], "Python 3.10 or newer is needed (found {version:?})");
+ Ok(exe)
+}
+
+fn helper(ctx: &Ctx, python: &str, mode: &str, job: Value, app_args: &[String]) -> Result<Output> {
+ let runner = ctx.fast.join("runner.py");
+ fs::write(&runner, RUNNER)?;
+ let job_path = ctx.fast.join(format!("job-{mode}.json"));
+ fs::write(&job_path, serde_json::to_vec_pretty(&job)?)?;
+ let out = output(
+ Command::new(python)
+ .arg(&runner)
+ .arg(mode)
+ .arg(&job_path)
+ .arg("--")
+ .args(app_args)
+ .current_dir(&ctx.root)
+ .env("PYTHONIOENCODING", "utf-8")
+ .env("PYTHONUTF8", "1")
+ .stdin(Stdio::null()),
+ "python",
+ )?;
+ if !out.status.success() {
+ bail!("the python {mode} run failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ }
+ Ok(out)
+}
+
+pub fn profile(ctx: &Ctx, python: &str, app_args: &[String]) -> Result<Profile> {
+ let out = ctx.fast.join("profile.json");
+ helper(ctx, python, "profile", json!({ "root": ctx.root, "out": out, "max": 40 }), app_args)?;
+ serde_json::from_str(&fs::read_to_string(&out)?).context("reading the profile")
+}
+
+const MAIN_GUARD: &[&str] =
+ &["if__name__==\"__main__\":", "if__name__=='__main__':", "if\"__main__\"==__name__:", "if'__main__'==__name__:"];
+
+fn main_guard(text: &str) -> Option<usize> {
+ backend::line_starting(text, MAIN_GUARD)
+}
+
+pub fn record(
+ ctx: &Ctx,
+ python: &str,
+ app_args: &[String],
+ hs: &Hotspot,
+ out: &Path,
+ limit: usize,
+) -> Result<Recording> {
+ let module = hs.module.as_deref().context("this function can't be imported")?;
+ let meta = out.with_extension("meta.json");
+ let job = json!({ "module": module, "func": hs.name, "out": out, "meta": meta, "limit": limit });
+ if module != "__main__" {
+ helper(ctx, python, "record", job, app_args)?;
+ } else {
+ // The entry script can't be patched from outside: insert a wrapping line before its
+ // if __name__ == "__main__" block for this run, then put the file back byte for byte.
+ let file = ctx.root.join(&hs.file);
+ let original = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;
+ let backup_dir = ctx.fast.join("backup");
+ fs::create_dir_all(&backup_dir)?;
+ let backup = backup_dir.join(crate::util::slug(&hs.file));
+ fs::write(&backup, &original)?;
+ let f = &hs.name;
+ let wrap = format!("try:\n {f} = __fast_anything_wrap__({f})\nexcept NameError:\n pass");
+ fs::write(&file, backend::insert_marked(&original, "#", &format!("recording {}", hs.id), &wrap, main_guard))?;
+ let run = helper(ctx, python, "record", job, app_args);
+ fs::write(&file, &original)
+ .with_context(|| format!("restoring {} (a copy is in {})", hs.file, backup.display()))?;
+ let _ = fs::remove_file(&backup);
+ run?;
+ }
+ serde_json::from_str(&fs::read_to_string(&meta)?).context("reading the recording summary")
+}
+
+// ------------------------------------------------------------------ the Rust crate
+
+/// Rust type for a Python annotation, if there's an obvious one.
+pub fn rust_type(annotation: &str, owned: bool) -> Option<String> {
+ let a: String = annotation.chars().filter(|c| !c.is_whitespace()).collect();
+ let a = a.trim_start_matches("typing.");
+ let inner = |prefix: &[&str]| {
+ prefix
+ .iter()
+ .find_map(|p| a.strip_prefix(p).and_then(|r| r.strip_prefix('[')).and_then(|r| r.strip_suffix(']')))
+ };
+ if let Some(x) = a.strip_suffix("|None").or_else(|| a.strip_prefix("None|")).or_else(|| inner(&["Optional"])) {
+ return rust_type(x, owned).map(|t| format!("Option<{t}>"));
+ }
+ Some(match a {
+ "int" => "i64".into(),
+ "float" => "f64".into(),
+ "bool" => "bool".into(),
+ "str" if owned => "String".into(),
+ "str" => "&str".into(),
+ "bytes" if !owned => "&[u8]".into(),
+ "None" if owned => "()".into(),
+ _ => {
+ if let Some(x) = inner(&["list", "List", "Sequence"]) {
+ format!("Vec<{}>", rust_type(x, true)?)
+ } else if let Some(x) = inner(&["tuple", "Tuple"]) {
+ let parts: Option<Vec<String>> = split_top(x).iter().map(|p| rust_type(p, true)).collect();
+ let parts = parts?;
+ if parts.iter().any(|p| p == "...") {
+ return None;
+ }
+ if parts.len() == 1 { format!("({},)", parts[0]) } else { format!("({})", parts.join(", ")) }
+ } else if let Some(x) = inner(&["dict", "Dict", "Mapping"]) {
+ let kv = split_top(x);
+ if kv.len() != 2 {
+ return None;
+ }
+ format!("std::collections::HashMap<{}, {}>", rust_type(&kv[0], true)?, rust_type(&kv[1], true)?)
+ } else {
+ let x = inner(&["set", "Set", "frozenset"])?;
+ format!("std::collections::HashSet<{}>", rust_type(x, true)?)
+ }
+ }
+ })
+}
+
+/// Split "a,b[c,d],e" on top-level commas.
+fn split_top(s: &str) -> Vec<String> {
+ let (mut depth, mut cur, mut out) = (0, String::new(), vec![]);
+ for c in s.chars() {
+ match c {
+ '[' => depth += 1,
+ ']' => depth -= 1,
+ ',' if depth == 0 => {
+ out.push(std::mem::take(&mut cur));
+ continue;
+ }
+ _ => {}
+ }
+ cur.push(c);
+ }
+ out.push(cur);
+ out
+}
+
+const RUST_KEYWORDS: &[&str] = &[
+ "as", "async", "await", "box", "break", "const", "continue", "crate", "do", "dyn", "else", "enum", "extern",
+ "false", "final", "fn", "for", "gen", "if", "impl", "in", "let", "loop", "macro", "match", "mod", "move", "mut",
+ "override", "priv", "pub", "ref", "return", "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe",
+ "unsized", "use", "virtual", "where", "while", "yield",
+];
+
+fn ident(name: &str) -> String {
+ if RUST_KEYWORDS.contains(&name) { format!("r#{name}") } else { name.to_string() }
+}
+
+/// A Python default value as a PyO3 signature default, if it's a simple literal.
+fn rust_default(value: &str) -> Option<String> {
+ let v = value.trim();
+ Some(match v {
+ "None" => "None".into(),
+ "True" => "true".into(),
+ "False" => "false".into(),
+ _ if v.parse::<i64>().is_ok() || v.parse::<f64>().is_ok() => v.into(),
+ _ if (v.starts_with('"') && v.ends_with('"')) || (v.starts_with('\'') && v.ends_with('\'')) => {
+ format!("{:?}", &v[1..v.len() - 1])
+ }
+ _ => return None,
+ })
+}
+
+pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {
+ let params: Vec<String> = hs
+ .params
+ .iter()
+ .map(|p| {
+ let ty =
+ p.annotation.as_deref().and_then(|a| rust_type(a, false)).unwrap_or_else(|| "&Bound<'_, PyAny>".into());
+ let ty = if p.default.as_deref() == Some("None") && !ty.starts_with("Option<") {
+ format!("Option<{ty}>")
+ } else {
+ ty
+ };
+ format!("{}: {ty}", ident(&p.name))
+ })
+ .collect();
+ let signature = if hs.params.iter().any(|p| p.default.is_some()) {
+ let parts: Vec<String> = hs
+ .params
+ .iter()
+ .map(|p| match p.default.as_deref().and_then(rust_default) {
+ Some(d) => format!("{} = {d}", ident(&p.name)),
+ None => ident(&p.name),
+ })
+ .collect();
+ format!("#[pyo3(signature = ({}))]\n", parts.join(", "))
+ } else {
+ String::new()
+ };
+ let ret = hs.returns.as_deref().and_then(|a| rust_type(a, true)).unwrap_or_else(|| "Py<PyAny>".into());
+ format!(
+ "//! Rust port of {id} ({file}:{line}), generated by fast-anything.\n\
+ //! Replace the todo!() with a faithful, fast port. TASK.md has the original and real calls.\n\
+ //! Check it with: fast-anything verify {id}\n\n\
+ use pyo3::prelude::*;\n\n\
+ #[pyfunction]\n\
+ {signature}\
+ #[allow(unused_variables)]\n\
+ fn {func}({params}) -> PyResult<{ret}> {{\n todo!(\"port {id}\")\n}}\n\n\
+ #[pymodule]\n\
+ fn {ext}(m: &Bound<'_, PyModule>) -> PyResult<()> {{\n m.add_function(wrap_pyfunction!({func}, m)?)?;\n Ok(())\n}}\n",
+ id = port.id,
+ file = hs.file,
+ line = hs.line,
+ func = ident(&hs.name),
+ params = params.join(", "),
+ ext = port.ext,
+ )
+}
+
+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]\npyo3 = {{ version = \"{PYO3}\", features = [\"extension-module\", \"abi3-py310\"] }}\n\n\
+ [profile.release]\nopt-level = 3\nlto = \"fat\"\ncodegen-units = 1\n\n\
+ # A crate of its own, even inside another Cargo workspace.\n[workspace]\n",
+ id = port.id,
+ ext = port.ext,
+ )
+}
+
+/// Render a recorded JSON value the way Python would print it.
+fn py_value(v: &Value) -> String {
+ match v {
+ Value::Null => "None".into(),
+ Value::Bool(b) => {
+ if *b {
+ "True".into()
+ } else {
+ "False".into()
+ }
+ }
+ Value::Number(n) => n.to_string(),
+ Value::String(s) => serde_json::to_string(s).unwrap_or_default(),
+ Value::Array(items) => format!("[{}]", items.iter().map(py_value).collect::<Vec<_>>().join(", ")),
+ Value::Object(map) => match map.iter().next() {
+ Some((tag, Value::Array(items))) if tag == "$tuple" => {
+ let inner: Vec<String> = items.iter().map(py_value).collect();
+ if inner.len() == 1 { format!("({},)", inner[0]) } else { format!("({})", inner.join(", ")) }
+ }
+ Some((tag, Value::Array(items))) if tag == "$set" => {
+ format!("{{{}}}", items.iter().map(py_value).collect::<Vec<_>>().join(", "))
+ }
+ Some((tag, Value::Array(pairs))) if tag == "$dict" => {
+ let inner: Vec<String> = pairs
+ .iter()
+ .filter_map(|p| p.as_array())
+ .filter(|p| p.len() == 2)
+ .map(|p| format!("{}: {}", py_value(&p[0]), py_value(&p[1])))
+ .collect();
+ format!("{{{}}}", inner.join(", "))
+ }
+ Some((tag, Value::String(s))) if tag == "$bytes" => format!("bytes(base64={s})"),
+ Some((tag, Value::String(s))) if tag == "$float" => format!("float({s:?})"),
+ _ => v.to_string(),
+ },
+ }
+}
+
+fn clip(s: &str, n: usize) -> String {
+ if s.chars().count() <= n { s.to_string() } else { format!("{}…", s.chars().take(n - 1).collect::<String>()) }
+}
+
+pub fn sample_calls(path: &Path, func: &str, n: usize) -> Vec<String> {
+ let Ok(text) = fs::read_to_string(path) else { return vec![] };
+ text.lines()
+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())
+ .take(n)
+ .map(|case| {
+ let mut args: Vec<String> =
+ case["args"].as_array().map(|a| a.iter().map(py_value).collect()).unwrap_or_default();
+ if let Some(kw) = case["kwargs"].as_object() {
+ args.extend(kw.iter().map(|(k, v)| format!("{k}={}", py_value(v))));
+ }
+ let outcome = match case.get("raises") {
+ Some(e) => format!("raises {}", e.as_str().unwrap_or("an exception")),
+ None => py_value(&case["result"]),
+ };
+ format!("{} -> {}", clip(&format!("{func}({})", args.join(", ")), 110), clip(&outcome, 60))
+ })
+ .collect()
+}
+
+pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path) -> String {
+ let fence = "```";
+ let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
+ let mut notes = String::new();
+ for w in &hs.warnings {
+ notes.push_str(&format!("- Note: {w}.\n"));
+ }
+ format!(
+ "# Port `{id}` to Rust\n\n\
+You're in a Rust crate fast-anything generated for this: `{dir}`.\n\
+Write `{func}` in `src/lib.rs` so it behaves **exactly** like the Python below, and runs fast.\n\
+Only edit files in this folder. Don't touch the Python project.\n\n\
+## The original ({file}:{line})\n\n{fence}python\n{source}\n{fence}\n\n\
+{helpers}## Real calls\n\n\
+fast-anything recorded {recorded} real calls (out of {seen} while the app ran). 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\
+- Python `str` indexes by Unicode code point: use `.chars()` (or bytes only after checking `is_ascii()`).\n\
+- Python ints don't overflow. `i64` is fine unless the recorded values are bigger.\n\
+- Float results are compared with a relative tolerance of 1e-9. Keep the same order of operations.\n\
+- Where Python raises, raise too (`PyValueError::new_err(...)`, `PyKeyError`, ...).\n\
+- Make it fast: no needless allocation or cloning, borrow inputs, `with_capacity`, fast paths for common cases.\n\
+- std only, unless a crate clearly pays off. Keep the function and module names as they are.\n\
+{notes}\n\
+## Check\n\n\
+Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all {recorded} recorded calls against it\n\
+(`fast-anything verify {id}`).\n",
+ id = port.id,
+ dir = crate_dir.display(),
+ func = hs.name,
+ file = hs.file,
+ line = hs.line,
+ source = hs.source,
+ recorded = port.recorded,
+ seen = crate::util::thousands(port.calls_seen),
+ helpers = helpers_md(hs, helpers),
+ )
+}
+
+/// Create the crate (never overwriting a src/lib.rs that's already there) and its TASK.md.
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ let dir = ctx.crate_dir(port);
+ fs::create_dir_all(dir.join("src"))?;
+ fs::create_dir_all(dir.join(".cargo"))?;
+ fs::write(dir.join("Cargo.toml"), cargo_toml(port))?;
+ fs::write(dir.join(".cargo/config.toml"), backend::CARGO_CONFIG)?;
+ let lib = dir.join("src/lib.rs");
+ if !lib.exists() {
+ fs::write(&lib, lib_rs(hs, port))?;
+ }
+ let task = task_md(hs, helpers, port, &dir);
+ fs::write(dir.join("TASK.md"), &task)?;
+ Ok(task)
+}
+
+/// TASK.md section listing the same-file functions the target calls, to port alongside it.
+pub fn helpers_md(hs: &Hotspot, helpers: &[Hotspot]) -> String {
+ if hs.calls.is_empty() {
+ return String::new();
+ }
+ let mut out = "## Helpers it calls\n\nPort these as private Rust functions in the same crate (they stay in Python for everyone else).\n\n".to_string();
+ for name in &hs.calls {
+ match helpers.iter().find(|h| &h.name == name) {
+ Some(h) => out.push_str(&format!("```python\n{}\n```\n\n", h.source)),
+ None => out.push_str(&format!("- `{name}`: read it in {}\n", hs.file)),
+ }
+ }
+ out
+}
+
+// ------------------------------------------------------------------ verify
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ let python = ctx.runtime()?;
+ let dir = ctx.crate_dir(port);
+ let out = dir.join("verify.json");
+ let job = json!({
+ "base": ctx.base_dir(), "libdir": ctx.lib_dir(), "ext": port.ext, "module": port.module,
+ "module_file": ctx.root.join(&port.file),
+ "func": port.func, "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ });
+ helper(ctx, python, "verify", job, &[])?;
+ let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
+ v.built = true;
+ Ok(v)
+}
+
+// ------------------------------------------------------------------ the shim
+
+/// Lines appended to the module (between markers) that swap in the Rust function.
+pub fn shim(port: &Port, lib_rel: &str) -> String {
+ let f = &port.func;
+ [
+ "# Uses the verified Rust port. FAST_ANYTHING_DISABLE=1 runs the Python above instead.",
+ &format!("# Undo with: fast-anything disable {}", port.id),
+ "def _fast_anything_load():",
+ " import os, sys",
+ " if os.environ.get(\"FAST_ANYTHING_DISABLE\"):",
+ " return None",
+ &format!(" lib = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), \"{lib_rel}\"))"),
+ " if lib not in sys.path:",
+ " sys.path.append(lib)",
+ " try:",
+ &format!(" from {} import {f}", port.ext),
+ " except ImportError:",
+ " return None",
+ &format!(" return {f}"),
+ &format!("{f} = _fast_anything_load() or {f}"),
+ "del _fast_anything_load",
+ ]
+ .join("\n")
+}
+
+pub fn strip_shim(text: &str, id: &str) -> String {
+ backend::strip_marked(text, "#", id)
+}
+
+pub fn add_shim(text: &str, port: &Port, lib_rel: &str) -> String {
+ if port.module == "__main__" {
+ // before the if __name__ == "__main__" block, so the app's main code sees the Rust version
+ backend::insert_marked(text, "#", &port.id, &shim(port, lib_rel), main_guard)
+ } else {
+ backend::append_marked(text, "#", &port.id, &shim(port, lib_rel))
+ }
+}
+
+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ let from = file.parent().context("module has no folder")?;
+ let lib_rel = forward_slashes(&relative(from, &ctx.lib_dir()));
+ fs::write(&file, add_shim(&text, port, &lib_rel)).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, strip_shim(&text, &port.id)).with_context(|| format!("writing {}", port.file))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn port() -> Port {
+ Port {
+ id: "fuzzy.levenshtein".into(),
+ file: "fuzzy.py".into(),
+ module: "fuzzy".into(),
+ func: "levenshtein".into(),
+ ext: "fa_fuzzy_levenshtein".into(),
+ crate_dir: ".fast/ports/fuzzy.levenshtein".into(),
+ recorded: 3,
+ calls_seen: 10,
+ verify: None,
+ enabled: false,
+ lang: crate::backend::Lang::Python,
+ owner: None,
+ }
+ }
+
+ #[test]
+ fn shim_round_trips() {
+ for original in ["def f():\n return 1\n", "def f():\r\n return 1\r\n", "x = 1"] {
+ let on = add_shim(original, &port(), ".fast/lib");
+ assert!(on.contains("from fa_fuzzy_levenshtein import levenshtein"));
+ assert_eq!(add_shim(&on, &port(), ".fast/lib"), on, "enabling twice changes nothing");
+ let off = strip_shim(&on, "fuzzy.levenshtein");
+ assert_eq!(off.trim_end(), original.trim_end());
+ if original.ends_with('\n') {
+ assert_eq!(off, original);
+ }
+ }
+ }
+
+ #[test]
+ fn maps_annotations() {
+ assert_eq!(rust_type("str", false).as_deref(), Some("&str"));
+ assert_eq!(rust_type("str", true).as_deref(), Some("String"));
+ assert_eq!(rust_type("list[int]", false).as_deref(), Some("Vec<i64>"));
+ assert_eq!(rust_type("List[str]", false).as_deref(), Some("Vec<String>"));
+ assert_eq!(rust_type("tuple[int, float]", true).as_deref(), Some("(i64, f64)"));
+ assert_eq!(rust_type("tuple[int]", true).as_deref(), Some("(i64,)"));
+ assert_eq!(
+ rust_type("dict[str, list[float]]", true).as_deref(),
+ Some("std::collections::HashMap<String, Vec<f64>>")
+ );
+ assert_eq!(rust_type("float | None", false).as_deref(), Some("Option<f64>"));
+ assert_eq!(rust_type("Optional[int]", false).as_deref(), Some("Option<i64>"));
+ assert_eq!(rust_type("MyClass", false), None);
+ assert_eq!(rust_type("tuple[int, ...]", true), None);
+ }
+
+ #[test]
+ fn renders_python_values() {
+ let v: Value =
+ serde_json::from_str(r#"[null, true, "a", {"$tuple": [1, 2]}, {"$dict": [["k", 1.5]]}]"#).unwrap();
+ assert_eq!(py_value(&v), r#"[None, True, "a", (1, 2), {"k": 1.5}]"#);
+ }
+
+ #[test]
+ fn spots_python() {
+ assert!(is_python("python"));
+ assert!(is_python("python3.12"));
+ assert!(is_python(".venv/bin/python"));
+ assert!(is_python("C:\\Python313\\python.exe"));
+ assert!(is_python("py"));
+ assert!(!is_python("node"));
+ }
+}
diff --git a/src/python/runner.py b/src/python/runner.py
new file mode 100644
index 0000000..c15c2b2
--- /dev/null
+++ b/src/python/runner.py
@@ -0,0 +1,578 @@
+"""Python side of fast-anything.
+
+The fast-anything CLI copies this file to <project>/.fast/runner.py and runs it as
+ python runner.py <mode> <job.json> -- <the app's python arguments>
+Modes: profile, record, verify. Not meant to be run by hand.
+"""
+
+import ast
+import base64
+import functools
+import importlib
+import importlib.util
+import json
+import math
+import os
+import random
+import runpy
+import sys
+import time
+
+DISABLE_ENV = "FAST_ANYTHING_DISABLE"
+SKIP_DIRS = {".fast", ".git", "venv", ".venv", "env", ".env", "site-packages", "dist-packages",
+ "node_modules", "__pycache__", "build", "dist", ".tox", ".nox"}
+IO_NAMES = {"print", "open", "input", "exec", "eval", "compile", "__import__", "breakpoint", "exit", "quit"}
+IO_MODULES = {"os", "sys", "subprocess", "socket", "requests", "urllib", "http", "httpx", "aiohttp", "shutil",
+ "pathlib", "logging", "sqlite3", "tempfile", "glob", "asyncio", "threading", "multiprocessing", "io"}
+NONDET_MODULES = {"random", "time", "datetime", "uuid", "secrets"}
+ARRAY_LIBS = {"np", "numpy", "pd", "pandas", "torch", "scipy", "numba", "polars", "pl"}
+
+
+# ------------------------------------------------------------------ values
+
+class Unsupported(Exception):
+ """A value that can't be recorded as plain data."""
+
+
+def enc(v):
+ if v is None or isinstance(v, (bool, int, str)):
+ return v
+ if isinstance(v, float):
+ return v if math.isfinite(v) else {"$float": repr(v)}
+ if isinstance(v, list):
+ return [enc(x) for x in v]
+ if isinstance(v, tuple):
+ return {"$tuple": [enc(x) for x in v]}
+ if isinstance(v, (bytes, bytearray)):
+ return {"$bytes": base64.b64encode(bytes(v)).decode("ascii")}
+ if isinstance(v, dict):
+ return {"$dict": [[enc(k), enc(x)] for k, x in v.items()]}
+ if isinstance(v, (set, frozenset)):
+ return {"$set": [enc(x) for x in v]}
+ raise Unsupported(type(v).__name__)
+
+
+def dec(v):
+ if isinstance(v, list):
+ return [dec(x) for x in v]
+ if isinstance(v, dict):
+ ((tag, x),) = v.items()
+ if tag == "$tuple":
+ return tuple(dec(i) for i in x)
+ if tag == "$bytes":
+ return base64.b64decode(x)
+ if tag == "$dict":
+ return {dec(k): dec(i) for k, i in x}
+ if tag == "$set":
+ return {dec(i) for i in x}
+ if tag == "$float":
+ return float(x)
+ raise ValueError("unknown tag " + tag)
+ return v
+
+
+def same(a, b):
+ """Equality the way a caller would see it: list == tuple, floats within 1e-9."""
+ if isinstance(a, bool) or isinstance(b, bool):
+ return type(a) is type(b) and a == b
+ if isinstance(a, float) or isinstance(b, float):
+ if not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
+ return False
+ if math.isnan(a) or math.isnan(b):
+ return math.isnan(a) and math.isnan(b)
+ return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)
+ if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
+ return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
+ if isinstance(a, dict) and isinstance(b, dict):
+ return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)
+ return a == b
+
+
+def show(v, limit=160):
+ text = repr(v)
+ return text if len(text) <= limit else text[: limit - 1] + "…"
+
+
+# ------------------------------------------------------------------ running the app
+
+def parse_target(argv):
+ args = list(argv)
+ while args and args[0].startswith("-") and args[0] != "-m":
+ flag = args.pop(0)
+ if flag == "-c":
+ sys.exit("fast-anything: 'python -c' isn't supported; point it at a script or a module")
+ if flag in ("-X", "-W") and args:
+ args.pop(0)
+ if not args:
+ sys.exit("fast-anything: give the app as 'python script.py ...' or 'python -m package ...'")
+ if args[0] == "-m":
+ if len(args) < 2:
+ sys.exit("fast-anything: -m needs a module name")
+ return "module", args[1], args[2:]
+ return "script", args[0], args[1:]
+
+
+def prepare_path(kind, target):
+ """Make sys.path look like a normal 'python ...' run. Returns (entry file, import base)."""
+ here = os.path.dirname(os.path.abspath(__file__))
+ sys.path[:] = [p for p in sys.path if os.path.abspath(p or ".") != here]
+ if kind == "script":
+ entry = os.path.abspath(target)
+ base = os.path.dirname(entry)
+ sys.path.insert(0, base)
+ return entry, base
+ base = os.getcwd()
+ sys.path.insert(0, base)
+ entry = None
+ try:
+ spec = importlib.util.find_spec(target)
+ if spec is not None and spec.submodule_search_locations:
+ spec = importlib.util.find_spec(target + ".__main__")
+ if spec is not None and spec.origin:
+ entry = os.path.abspath(spec.origin)
+ except (ImportError, ValueError):
+ pass
+ return entry, base
+
+
+def run_target(kind, target, rest):
+ sys.argv = [target] + list(rest)
+ try:
+ if kind == "script":
+ runpy.run_path(target, run_name="__main__")
+ else:
+ runpy.run_module(target, run_name="__main__", alter_sys=True)
+ except SystemExit as e:
+ if e.code not in (None, 0):
+ raise
+
+
+# ------------------------------------------------------------------ static analysis
+
+_files = {}
+
+
+def parse_file(path):
+ if path not in _files:
+ try:
+ with open(path, encoding="utf-8") as f:
+ src = f.read()
+ tree = ast.parse(src)
+ except (OSError, SyntaxError, UnicodeDecodeError, ValueError):
+ _files[path] = None
+ return None
+ by_line, top = {}, set()
+
+ def walk(node, prefix, kind):
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ qual = prefix + child.name
+ for line in [child.lineno] + [d.lineno for d in child.decorator_list]:
+ by_line[line] = (child, qual, kind)
+ if kind == "function":
+ top.add(child.name)
+ walk(child, qual + ".<locals>.", "nested")
+ elif isinstance(child, ast.ClassDef):
+ walk(child, prefix + child.name + ".", "method" if kind == "function" else "nested")
+ else:
+ walk(child, prefix, kind)
+
+ walk(tree, "", "function")
+ guard = next((n.lineno for n in tree.body if isinstance(n, ast.If) and is_main_guard(n.test)), None)
+ _files[path] = (src, by_line, top, guard)
+ return _files[path]
+
+
+def is_main_guard(test):
+ """if __name__ == "__main__" (either way round)."""
+ if not (isinstance(test, ast.Compare) and len(test.ops) == 1 and isinstance(test.ops[0], ast.Eq)):
+ return False
+ sides = [test.left, test.comparators[0]]
+ names = [s for s in sides if isinstance(s, ast.Name) and s.id == "__name__"]
+ consts = [s for s in sides if isinstance(s, ast.Constant) and s.value == "__main__"]
+ return len(names) == 1 and len(consts) == 1
+
+
+def dotted(node):
+ parts = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return list(reversed(parts))
+ return None
+
+
+def module_name(path, entry, base):
+ ap = os.path.abspath(path)
+ if entry and os.path.normcase(ap) == os.path.normcase(entry):
+ return "__main__"
+ try:
+ rel = os.path.relpath(ap, base)
+ except ValueError:
+ return None
+ if rel.startswith(os.pardir) or not rel.endswith(".py"):
+ return None
+ parts = rel[:-3].split(os.sep)
+ if parts[-1] == "__init__":
+ parts.pop()
+ if not parts or not all(p.isidentifier() for p in parts):
+ return None
+ return ".".join(parts)
+
+
+def describe(path, line, name, entry, base):
+ parsed = parse_file(path)
+ if parsed is None:
+ return None
+ src, by_line, top, guard = parsed
+ hit = by_line.get(line)
+ if hit is None or hit[0].name != name:
+ return None
+ node, qualname, kind = hit
+ module = module_name(path, entry, base)
+
+ blockers, warnings, factor = [], [], 1.0
+ if module is None:
+ blockers.append("can't be imported from the app's folder")
+ elif module == "__main__" and guard is None:
+ blockers.append("lives in the entry script, which runs on import: put that code under if __name__ == '__main__'")
+ elif module == "__main__" and node.lineno > guard:
+ blockers.append("defined inside the if __name__ == '__main__' block")
+ if kind == "method":
+ blockers.append("method (v0.1 ports module-level functions)")
+ elif kind == "nested":
+ blockers.append("nested function")
+ if isinstance(node, ast.AsyncFunctionDef):
+ blockers.append("async")
+
+ args = node.args
+ if args.vararg or args.kwarg:
+ warnings.append("takes *args/**kwargs")
+ factor *= 0.7
+
+ io, nondet, arrays, helpers = set(), set(), set(), set()
+ is_generator = writes_globals = False
+ for sub in ast.walk(node):
+ if isinstance(sub, (ast.Yield, ast.YieldFrom)):
+ is_generator = True
+ elif isinstance(sub, (ast.Global, ast.Nonlocal)):
+ writes_globals = True
+ elif isinstance(sub, ast.Call):
+ target = dotted(sub.func)
+ if not target:
+ continue
+ head = target[0]
+ if len(target) == 1:
+ if head in IO_NAMES:
+ io.add(head)
+ elif head in top and head != node.name:
+ helpers.add(head)
+ elif head in IO_MODULES:
+ io.add(".".join(target))
+ elif head in NONDET_MODULES:
+ nondet.add(".".join(target))
+ elif head in ARRAY_LIBS:
+ arrays.add(head)
+ if is_generator:
+ blockers.append("generator (yield)")
+ if writes_globals:
+ blockers.append("writes global state")
+ if io:
+ blockers.append("does I/O: " + ", ".join(sorted(io)[:3]))
+ if nondet:
+ blockers.append("not deterministic: " + ", ".join(sorted(nondet)[:3]))
+ if arrays:
+ warnings.append("already uses " + ", ".join(sorted(arrays)) + ", less to gain")
+ factor *= 0.4
+ if helpers:
+ warnings.append("calls " + ", ".join(sorted(helpers)[:3]) + ", they get ported together with it")
+
+ positional = args.posonlyargs + args.args
+ defaults = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
+ params = [{"name": a.arg, "annotation": ast.unparse(a.annotation) if a.annotation else None,
+ "default": ast.unparse(d) if d is not None else None}
+ for a, d in zip(positional, defaults)]
+ params += [{"name": a.arg, "annotation": ast.unparse(a.annotation) if a.annotation else None,
+ "default": ast.unparse(d) if d is not None else None}
+ for a, d in zip(args.kwonlyargs, args.kw_defaults)]
+ returns = ast.unparse(node.returns) if node.returns else None
+ if returns is None or any(p["annotation"] is None for p in params):
+ warnings.append("missing type hints, types are inferred from recorded calls")
+ factor *= 0.9
+
+ lines = src.splitlines()
+ first = min([node.lineno] + [d.lineno for d in node.decorator_list])
+ return {
+ "qualname": qualname,
+ "module": module,
+ "kind": kind,
+ "end_line": node.end_lineno,
+ "params": params,
+ "returns": returns,
+ "blockers": blockers,
+ "warnings": warnings,
+ "portability": 0.0 if blockers else factor,
+ "calls": sorted(helpers),
+ "source": "\n".join(lines[first - 1: node.end_lineno]),
+ }
+
+
+def project_relative(root, path):
+ try:
+ rel = os.path.relpath(os.path.abspath(path), root)
+ except ValueError:
+ return None
+ if rel == os.pardir or rel.startswith(os.pardir + os.sep):
+ return None
+ if any(part in SKIP_DIRS for part in rel.split(os.sep)[:-1]):
+ return None
+ return rel
+
+
+# ------------------------------------------------------------------ modes
+
+def cmd_profile(job, argv):
+ import cProfile
+ import pstats
+
+ kind, target, rest = parse_target(argv)
+ entry, base = prepare_path(kind, target)
+ root = job["root"]
+ prof = cProfile.Profile()
+ start = time.perf_counter()
+ prof.enable()
+ try:
+ run_target(kind, target, rest)
+ finally:
+ prof.disable()
+ wall = time.perf_counter() - start
+
+ rows = []
+ for (path, line, name), (_cc, ncalls, tottime, cumtime, _callers) in pstats.Stats(prof).stats.items():
+ if name.startswith("<") or not path or path.startswith("<"):
+ continue
+ rel = project_relative(root, path)
+ if rel is not None:
+ rows.append((path, rel, line, name, ncalls, tottime, cumtime))
+ rows.sort(key=lambda r: r[6], reverse=True)
+
+ functions = []
+ for path, rel, line, name, ncalls, tottime, cumtime in rows[: job.get("max", 40)]:
+ info = describe(path, line, name, entry, base)
+ if info is None:
+ continue
+ info.update(file=rel.replace(os.sep, "/"), line=line, name=name,
+ ncalls=ncalls, tottime=tottime, cumtime=cumtime)
+ functions.append(info)
+
+ try:
+ base_rel = os.path.relpath(base, root)
+ except ValueError:
+ base_rel = base
+ with open(job["out"], "w", encoding="utf-8") as f:
+ json.dump({"wall": wall, "base": base_rel, "functions": functions}, f)
+
+
+def cmd_record(job, argv):
+ kind, target, rest = parse_target(argv)
+ prepare_path(kind, target)
+ os.environ[DISABLE_ENV] = "1" # always record the original Python
+ limit = int(job["limit"])
+ rng = random.Random(0xFA57)
+ kept = []
+ stats = {"calls": 0, "skipped": 0, "unsupported": set()}
+
+ def store(slot, case):
+ if len(kept) < limit:
+ kept.append(case)
+ else:
+ kept[slot % limit] = case
+
+ def wrap(original):
+ @functools.wraps(original)
+ def recorder(*args, **kwargs):
+ stats["calls"] += 1
+ slot = len(kept) if len(kept) < limit else rng.randrange(stats["calls"])
+ case = None
+ if slot < limit:
+ try: # encode before the call, in case the function mutates its arguments
+ case = {"args": enc(list(args)), "kwargs": {k: enc(v) for k, v in kwargs.items()}}
+ except Unsupported as e:
+ stats["skipped"] += 1
+ stats["unsupported"].add(str(e))
+ try:
+ result = original(*args, **kwargs)
+ except Exception as e:
+ if case is not None:
+ case["raises"] = type(e).__name__
+ store(slot, case)
+ raise
+ if case is not None:
+ try:
+ case["result"] = enc(result)
+ store(slot, case)
+ except Unsupported as e:
+ stats["skipped"] += 1
+ stats["unsupported"].add(str(e))
+ return result
+
+ return recorder
+
+ if job["module"] == "__main__":
+ # the entry script wraps the function itself, via a block fast-anything inserted
+ import builtins
+
+ builtins.__fast_anything_wrap__ = wrap
+ else:
+ module = importlib.import_module(job["module"])
+ setattr(module, job["func"], wrap(getattr(module, job["func"])))
+ run_target(kind, target, rest)
+
+ with open(job["out"], "w", encoding="utf-8") as f:
+ for case in kept:
+ f.write(json.dumps(case, ensure_ascii=False) + "\n")
+ with open(job["meta"], "w", encoding="utf-8") as f:
+ json.dump({"calls": stats["calls"], "kept": len(kept), "skipped": stats["skipped"],
+ "unsupported": sorted(stats["unsupported"])}, f)
+
+
+def cmd_verify(job, _argv):
+ os.environ[DISABLE_ENV] = "1"
+ sys.path.insert(0, job["base"])
+ sys.path.insert(0, job["libdir"])
+ fast = getattr(importlib.import_module(job["ext"]), job["func"])
+ if job["module"] == "__main__":
+ # import the entry script under another name: its if __name__ == "__main__" block won't run
+ spec = importlib.util.spec_from_file_location("_fast_anything_entry", job["module_file"])
+ entry = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = entry
+ spec.loader.exec_module(entry)
+ original = getattr(entry, job["func"])
+ else:
+ original = getattr(importlib.import_module(job["module"]), job["func"])
+
+ with open(job["cases"], encoding="utf-8") as f:
+ cases = [json.loads(line) for line in f if line.strip()]
+ recorded = len(cases)
+ derived = derive(original, cases, job.get("derive_budget", 3.0), job.get("derive_limit", 200))
+ cases += derived
+
+ report = {"total": len(cases), "derived": len(derived), "passed": 0, "failed": 0, "failures": []}
+ calls = []
+ for i, case in enumerate(cases):
+ args = dec(case["args"])
+ kwargs = {k: dec(v) for k, v in case.get("kwargs", {}).items()}
+ calls.append((args, kwargs))
+ try:
+ got, err = fast(*args, **kwargs), None
+ except (KeyboardInterrupt, SystemExit):
+ raise
+ except BaseException as e: # Rust panics arrive as PanicException (a BaseException)
+ got, err = None, e
+ if "raises" in case:
+ ok, expected = err is not None, "raises " + case["raises"]
+ else:
+ want = dec(case["result"])
+ ok, expected = err is None and same(want, got), show(want)
+ if ok:
+ report["passed"] += 1
+ continue
+ report["failed"] += 1
+ if len(report["failures"]) < 8:
+ shown = [show(a, 80) for a in args] + [k + "=" + show(v, 80) for k, v in kwargs.items()]
+ report["failures"].append({
+ "case": i,
+ "call": ("(derived) " if case.get("derived") else "") + job["func"] + "(" + ", ".join(shown) + ")",
+ "expected": expected,
+ "got": show(got) if err is None else "raised " + type(err).__name__ + ": " + show(str(err), 200),
+ })
+
+ if cases and report["failed"] == 0:
+ calls = calls[:recorded]
+ py = best_pass(original, calls, job.get("budget", 0.5))
+ rs = best_pass(fast, calls, job.get("budget", 0.5))
+ report["micro"] = {"original_ns": py / len(calls) * 1e9, "rust_ns": rs / len(calls) * 1e9,
+ "speedup": py / rs if rs > 0 else 0.0}
+
+ with open(job["out"], "w", encoding="utf-8") as f:
+ json.dump(report, f)
+
+
+SLICE_LENGTHS = (0, 1, 2, 3, 5, 8, 13, 21, 34, 55)
+
+
+def variants(value, rng):
+ """Smaller versions of a list/str/bytes/tuple argument: empty, tiny, and random slices."""
+ if not isinstance(value, (list, tuple, str, bytes)) or len(value) < 2:
+ return []
+ n = len(value)
+ out = []
+ for length in SLICE_LENGTHS:
+ if length < n:
+ for _ in range(1 if length < 2 else 3):
+ start = rng.randrange(n - length + 1)
+ out.append(value[start:start + length])
+ return out
+
+
+def derive(original, cases, budget, limit):
+ """Extra test cases: recorded calls with smaller inputs, answered by the original itself."""
+ import copy
+
+ rng = random.Random(0xFA57)
+ derived, seen, start = [], set(), time.perf_counter()
+ for case in cases:
+ if "raises" in case:
+ continue
+ args = dec(case["args"])
+ kwargs = {k: dec(v) for k, v in case.get("kwargs", {}).items()}
+ for i, arg in enumerate(args):
+ for smaller in variants(arg, rng):
+ if len(derived) >= limit or time.perf_counter() - start > budget:
+ return derived
+ new_args = list(args)
+ new_args[i] = smaller
+ try:
+ encoded = {"args": enc(new_args), "kwargs": {k: enc(v) for k, v in kwargs.items()}}
+ key = json.dumps(encoded, sort_keys=True)
+ if key in seen:
+ continue
+ seen.add(key)
+ result = original(*copy.deepcopy(new_args), **copy.deepcopy(kwargs))
+ encoded["result"] = enc(result)
+ except Exception:
+ continue # outside the function's domain: not a fair test
+ encoded["derived"] = True
+ derived.append(encoded)
+ return derived
+
+
+def best_pass(fn, calls, budget):
+ """Fastest time to replay every recorded call once, within a time budget."""
+ best, spent, passes = float("inf"), 0.0, 0
+ while passes < 3 or (spent < budget and passes < 2000):
+ start = time.perf_counter()
+ for args, kwargs in calls:
+ try:
+ fn(*args, **kwargs)
+ except Exception:
+ pass
+ took = time.perf_counter() - start
+ best, spent, passes = min(best, took), spent + took, passes + 1
+ return best
+
+
+def main():
+ mode, job_path = sys.argv[1], sys.argv[2]
+ rest = sys.argv[3:]
+ if rest[:1] == ["--"]:
+ rest = rest[1:]
+ with open(job_path, encoding="utf-8") as f:
+ job = json.load(f)
+ {"profile": cmd_profile, "record": cmd_record, "verify": cmd_verify}[mode](job, rest)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/report.rs b/src/report.rs
new file mode 100644
index 0000000..4b5b30d
--- /dev/null
+++ b/src/report.rs
@@ -0,0 +1,110 @@
+//! A report worth sharing: markdown for the PR, an SVG card for the README / socials.
+
+use crate::bench::BenchResult;
+use crate::state::{Ctx, Port};
+use crate::util::{nanos, secs, times};
+use anyhow::{Context, Result};
+use serde::Serialize;
+use std::fs;
+use std::path::PathBuf;
+
+#[derive(Serialize)]
+pub struct ReportOut {
+ pub markdown: PathBuf,
+ pub svg: PathBuf,
+ pub text: String,
+}
+
+fn xml(s: &str) -> String {
+ s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+}
+
+fn port_line(p: &Port) -> String {
+ let v = p.verify.clone().unwrap_or_default();
+ match v.micro {
+ Some(m) => format!("{} → Rust · {} per call · {}/{} calls verified", p.id, times(m.speedup), v.passed, v.total),
+ None => format!("{} → Rust · {}/{} calls verified", p.id, v.passed, v.total),
+ }
+}
+
+pub fn svg(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
+ let headline = times(b.speedup);
+ let after_w = (300.0 * b.after.median / b.before.median.max(1e-12)).clamp(4.0, 300.0);
+ let detail = ports.iter().take(2).map(|p| port_line(p)).collect::<Vec<_>>().join(" ");
+ let sans = "system-ui,-apple-system,Segoe UI,Helvetica,Arial,sans-serif";
+ let mono = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace";
+ format!(
+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="760" height="220" viewBox="0 0 760 220" role="img" aria-label="{project}: {headline} faster">
+ <rect width="760" height="220" rx="16" fill="#0d1117"/>
+ <rect x="0.5" y="0.5" width="759" height="219" rx="15.5" fill="none" stroke="#30363d"/>
+ <text x="32" y="44" font-family="{mono}" font-size="14" fill="#f74c00">⚡ fast-anything</text>
+ <text x="32" y="78" font-family="{sans}" font-size="20" fill="#e6edf3">{project}</text>
+ <text x="32" y="148" font-family="{sans}" font-size="64" font-weight="800" fill="#f74c00">{headline}<tspan dx="12" font-size="28" font-weight="600" fill="#e6edf3">faster</tspan></text>
+ <text x="420" y="92" font-family="{sans}" font-size="13" fill="#8b949e">{original}</text>
+ <text x="720" y="92" font-family="{mono}" font-size="13" fill="#e6edf3" text-anchor="end">{before}</text>
+ <rect x="420" y="100" width="300" height="16" rx="4" fill="#30363d"/>
+ <text x="420" y="146" font-family="{sans}" font-size="13" fill="#8b949e">Rust</text>
+ <text x="720" y="146" font-family="{mono}" font-size="13" fill="#e6edf3" text-anchor="end">{after}</text>
+ <rect x="420" y="154" width="{after_w:.1}" height="16" rx="4" fill="#f74c00"/>
+ <text x="32" y="196" font-family="{sans}" font-size="13" fill="#8b949e">{detail}</text>
+</svg>
+"##,
+ project = xml(project),
+ original = b.lang.label(),
+ before = secs(b.before.median),
+ after = secs(b.after.median),
+ detail = xml(&detail),
+ )
+}
+
+pub fn markdown(project: &str, b: &BenchResult, ports: &[&Port]) -> String {
+ let mut md = format!(
+ "# ⚡ {project}: {} faster\n\n`{}` went from **{}** to **{}** (median of {} runs each, original and Rust interleaved).\n\n![fast-anything report](report.svg)\n\n| function | per call | checked against |\n|---|---|---|\n",
+ times(b.speedup),
+ b.command.join(" "),
+ secs(b.before.median),
+ secs(b.after.median),
+ b.runs
+ );
+ for p in ports {
+ let v = p.verify.clone().unwrap_or_default();
+ let per_call = v
+ .micro
+ .map(|m| format!("**{}** ({} → {})", times(m.speedup), nanos(m.original_ns), nanos(m.rust_ns)))
+ .unwrap_or_else(|| "n/a".into());
+ md.push_str(&format!("| `{}` | {per_call} | {}/{} recorded real calls |\n", p.id, v.passed, v.total));
+ }
+ md.push_str("\nThe original code stays in place: set `FAST_ANYTHING_DISABLE=1` to run it, or `fast-anything disable <id>` to remove the switch.\n\n<sub>Made with [fast-anything](https://github.com/EL4CTEO/fast-anything)</sub>\n");
+ md
+}
+
+pub fn write(ctx: &Ctx) -> Result<ReportOut> {
+ let b = ctx.state.bench.as_ref().context("no benchmark yet: run fast-anything bench")?;
+ let project = ctx.root.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "your app".into());
+ let ports: Vec<&Port> = ctx.state.ports.values().filter(|p| p.enabled).collect();
+ let text = markdown(&project, b, &ports);
+ let (md_path, svg_path) = (ctx.fast.join("report.md"), ctx.fast.join("report.svg"));
+ fs::write(&md_path, &text)?;
+ fs::write(&svg_path, svg(&project, b, &ports))?;
+ Ok(ReportOut { markdown: md_path, svg: svg_path, text })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::bench::Stats;
+
+ #[test]
+ fn svg_is_escaped_and_scaled() {
+ let b = BenchResult {
+ before: Stats { median: 4.0, ..Stats::default() },
+ after: Stats { median: 0.5, ..Stats::default() },
+ speedup: 8.0,
+ ..BenchResult::default()
+ };
+ let card = svg("a<b>&c", &b, &[]);
+ assert!(card.contains("a&lt;b&gt;&amp;c"));
+ assert!(card.contains("8.0×"));
+ assert!(card.contains(r#"width="37.5""#));
+ }
+}
diff --git a/src/ruby.rs b/src/ruby.rs
new file mode 100644
index 0000000..ab4ad87
--- /dev/null
+++ b/src/ruby.rs
@@ -0,0 +1,400 @@
+//! Ruby backend. No Ruby headers or libclang needed: the port is a plain Rust library with a
+//! C entry point that takes and returns JSON, called through Ruby's built-in Fiddle.
+//! The same bridge works for any language that can call C.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::Hotspot;
+use crate::python::DISABLE_ENV;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{combined, forward_slashes, output, relative, slug, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde_json::{Value, json};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output, Stdio};
+
+const RUNNER: &str = include_str!("ruby/runner.rb");
+const RECORDER: &str = include_str!("ruby/recorder.rb");
+const GUARDS: &[&str] = &["if__FILE__==$0", "if$0==__FILE__", "if__FILE__==$PROGRAM_NAME", "if$PROGRAM_NAME==__FILE__"];
+
+pub fn is_ruby(program: &str) -> bool {
+ let stem = Path::new(program).file_stem().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase();
+ stem == "ruby"
+}
+
+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(["-e", "puts RbConfig.ruby, RUBY_VERSION"]).current_dir(root), "ruby")?;
+ ensure!(out.status.success(), "{program} failed:\n{}", tail(&combined(&out), 5));
+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
+ let mut lines = text.lines();
+ let exe = lines.next().unwrap_or_default().trim().to_string();
+ let version: Vec<u32> = lines.next().unwrap_or_default().split('.').filter_map(|s| s.parse().ok()).collect();
+ ensure!(version.as_slice() >= &[3, 3][..], "Ruby 3.3 or newer is needed (found {version:?})");
+ Ok(exe)
+}
+
+fn main_guard(text: &str) -> Option<usize> {
+ backend::line_starting(text, GUARDS)
+}
+
+fn runner(ctx: &Ctx, ruby: &str, mode: &str, job: Value, app_args: &[String]) -> Result<Output> {
+ let script = ctx.fast.join("runner.rb");
+ fs::write(&script, RUNNER)?;
+ fs::write(ctx.fast.join("recorder.rb"), RECORDER)?;
+ let job_path = ctx.fast.join(format!("job-{mode}.json"));
+ fs::write(&job_path, serde_json::to_vec_pretty(&job)?)?;
+ let out = output(
+ Command::new(ruby)
+ .arg(&script)
+ .arg(mode)
+ .arg(&job_path)
+ .arg("--")
+ .args(app_args)
+ .current_dir(&ctx.root)
+ .stdin(Stdio::null()),
+ "ruby",
+ )?;
+ if !out.status.success() {
+ bail!("the ruby {mode} step failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ }
+ Ok(out)
+}
+
+pub fn profile(ctx: &Ctx, ruby: &str, args: &[String]) -> Result<Profile> {
+ let result = ctx.fast.join("profile.json");
+ runner(ctx, ruby, "profile", json!({ "root": ctx.root, "out": result }), args)?;
+ serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")
+}
+
+fn owner(hs_owner: Option<&str>) -> &str {
+ hs_owner.unwrap_or("Object")
+}
+
+/// Wrap the method for one run: a line appended to its file (or put before the entry script's
+/// "if __FILE__ == $0" block) hands it to the preloaded recorder. The file is restored afterwards.
+pub fn record(ctx: &Ctx, ruby: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
+ let file = ctx.root.join(&hs.file);
+ let original = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;
+ let backup_dir = ctx.fast.join("backup");
+ fs::create_dir_all(&backup_dir)?;
+ let backup = backup_dir.join(slug(&hs.file));
+ fs::write(&backup, &original)?;
+ let line = format!("$__fast_anything_wrap&.call({}, :{})", owner(hs.owner.as_deref()), hs.name);
+ let id = format!("recording {}", hs.id);
+ let patched = if hs.module.as_deref() == Some("__main__") {
+ backend::insert_marked(&original, "#", &id, &line, main_guard)
+ } else {
+ backend::append_marked(&original, "#", &id, &line)
+ };
+ fs::write(&file, patched)?;
+ let recorder = ctx.fast.join("recorder.rb");
+ fs::write(&recorder, RECORDER)?;
+ let meta = out.with_extension("meta.json");
+ let run = output(
+ Command::new(ruby)
+ .arg(format!("-r{}", recorder.display()))
+ .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()),
+ "ruby",
+ );
+ fs::write(&file, &original)
+ .with_context(|| format!("restoring {} (a copy is in {})", hs.file, backup.display()))?;
+ let _ = fs::remove_file(&backup);
+ let run = run?;
+ ensure!(run.status.success(), "the app failed while recording ({}):\n{}", run.status, tail(&combined(&run), 30));
+ serde_json::from_str(&fs::read_to_string(&meta)?).context("reading the recording summary")
+}
+
+// ------------------------------------------------------------------ the crate (C ABI, JSON in/out)
+
+/// A Ruby default value as JSON, if it's a simple literal.
+pub fn default_json(value: &str) -> Option<String> {
+ let v = value.trim();
+ Some(match v {
+ "nil" => "null".into(),
+ "true" | "false" | "[]" | "{}" => v.into(),
+ _ if v.replace('_', "").parse::<i64>().is_ok() => v.replace('_', ""),
+ _ if v.parse::<f64>().is_ok() => v.into(),
+ _ if v.len() >= 2
+ && ((v.starts_with('"') && v.ends_with('"')) || (v.starts_with('\'') && v.ends_with('\''))) =>
+ {
+ serde_json::to_string(&v[1..v.len() - 1]).ok()?
+ }
+ _ => return None,
+ })
+}
+
+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!(
+ "//! Rust port of {id} ({file}:{line}), generated by fast-anything.\n\
+ //! Replace the todo!() with a faithful, fast port, and the serde_json::Value types with real ones:\n\
+ //! Integer -> i64, Float -> f64, String -> String, Array -> Vec<_>, Hash -> HashMap<String, _>, nil -> Option<_>.\n\
+ //! Return Err(message) where Ruby would raise. Check it with: fast-anything verify {id}\n\n\
+ #[allow(unused_variables)]\n\
+ pub fn {func}({params}) -> Result<serde_json::Value, String> {{\n todo!(\"port {id}\")\n}}\n",
+ id = port.id,
+ file = hs.file,
+ line = hs.line,
+ func = snake(&hs.name),
+ params = params.join(", "),
+ )
+}
+
+fn 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| {
+ if s.chars().count() <= n { s } else { format!("{}…", s.chars().take(n - 1).collect::<String>()) }
+ };
+ text.lines()
+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())
+ .take(n)
+ .map(|case| {
+ let args: Vec<String> =
+ case["args"].as_array().map(|a| a.iter().map(|v| v.to_string()).collect()).unwrap_or_default();
+ let outcome = match case.get("raises") {
+ Some(e) => format!("raises {}", 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) -> String {
+ let fence = "```";
+ let samples = sample_calls(&crate_dir.join("recordings.jsonl"), &hs.name, 8).join("\n");
+ let mut helper_md = String::new();
+ if !hs.calls.is_empty() {
+ helper_md.push_str("## Helpers it calls\n\nPort these as private Rust functions in src/port.rs (they stay in Ruby 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}ruby\n{}\n{fence}\n\n", h.source)),
+ None => helper_md.push_str(&format!("- `{name}`: read it in {}\n", hs.file)),
+ }
+ }
+ }
+ format!(
+ "# Port `{id}` to Rust\n\n\
+You're in a Rust crate fast-anything generated for this: `{dir}`.\n\
+Write `{func}` in `src/port.rs` so it behaves **exactly** like the Ruby 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 Ruby project.\n\n\
+## The original ({file}:{line})\n\n{fence}ruby\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\
+- Change the `serde_json::Value` parameter and return types to concrete ones: they're deserialized for you.\n\
+- Ruby strings index by character: use `.chars()` (or bytes only after checking `is_ascii()`).\n\
+- Ruby Integers don't overflow. `i64` is fine unless the recorded values are bigger. Keep Integer vs Float as Ruby has it.\n\
+- Hash keys arrive as strings; return `Err(message)` where Ruby would raise.\n\
+- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases.\n\
+- Keep the function name.\n\n\
+## Check\n\n\
+Run `cargo check` here. Then fast-anything builds the crate in release mode and replays all recorded calls against it\n\
+(`fast-anything verify {id}`).\n",
+ id = port.id,
+ dir = crate_dir.display(),
+ func = hs.name,
+ file = hs.file,
+ line = hs.line,
+ source = hs.source,
+ recorded = port.recorded,
+ seen = crate::util::thousands(port.calls_seen),
+ )
+}
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ let dir = ctx.crate_dir(port);
+ fs::create_dir_all(dir.join("src"))?;
+ fs::create_dir_all(dir.join(".cargo"))?;
+ fs::write(dir.join("Cargo.toml"), cargo_toml(port))?;
+ fs::write(dir.join(".cargo/config.toml"), backend::CARGO_CONFIG)?;
+ fs::write(dir.join("src/lib.rs"), glue_rs(hs, port))?;
+ let body = dir.join("src/port.rs");
+ if !body.exists() {
+ fs::write(&body, port_rs(hs, port))?;
+ }
+ let task = task_md(hs, helpers, port, &dir);
+ fs::write(dir.join("TASK.md"), &task)?;
+ Ok(task)
+}
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ let ruby = ctx.runtime()?;
+ let dir = ctx.crate_dir(port);
+ let out = dir.join("verify.json");
+ let (_, lib) = backend::Lang::Ruby.artifact(&port.ext);
+ let job = json!({
+ "lib": ctx.lib_dir().join(lib), "func": port.func, "owner": owner(port.owner.as_deref()),
+ "module_file": ctx.root.join(&port.file), "cases": dir.join("recordings.jsonl"), "out": out, "budget": 0.5,
+ });
+ runner(ctx, ruby, "verify", job, &[])?;
+ let mut v: Verify = serde_json::from_str(&fs::read_to_string(&out)?).context("reading verify results")?;
+ v.built = true;
+ Ok(v)
+}
+
+// ------------------------------------------------------------------ the shim
+
+pub fn shim(port: &Port, lib_rel: &str) -> String {
+ let owner = owner(port.owner.as_deref());
+ let name = &port.func;
+ let mut lines = vec![
+ "# Uses the verified Rust port. FAST_ANYTHING_DISABLE=1 runs the Ruby above instead.".to_string(),
+ format!("# Undo with: fast-anything disable {}", port.id),
+ "unless ENV[\"FAST_ANYTHING_DISABLE\"]".to_string(),
+ " begin".to_string(),
+ " require \"fiddle\"".to_string(),
+ " require \"json\"".to_string(),
+ format!(" -> {{\n lib = Fiddle.dlopen(File.expand_path(\"{lib_rel}\", __dir__))"),
+ " call = Fiddle::Function.new(lib[\"fa_call\"], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T, Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP)".to_string(),
+ " free = Fiddle::Function.new(lib[\"fa_free\"], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T], Fiddle::TYPE_VOID)".to_string(),
+ format!(" {owner}.send(:define_method, :{name}) do |*args|"),
+ " input = JSON.generate(args)".to_string(),
+ " size = Fiddle::Pointer.malloc(Fiddle::SIZEOF_SIZE_T, Fiddle::RUBY_FREE)".to_string(),
+ " out = call.call(input, input.bytesize, size)".to_string(),
+ " len = size[0, Fiddle::SIZEOF_SIZE_T].unpack1(\"J\")".to_string(),
+ " reply = JSON.parse(out[0, len].force_encoding(Encoding::UTF_8))".to_string(),
+ " free.call(out, len)".to_string(),
+ " raise reply[\"error\"] if reply.key?(\"error\")".to_string(),
+ " reply[\"ok\"]".to_string(),
+ " end".to_string(),
+ ];
+ if owner == "Object" {
+ lines.push(format!(" Object.send(:private, :{name})"));
+ }
+ lines.extend([
+ " }.call".to_string(),
+ " rescue LoadError, Fiddle::DLError".to_string(),
+ " end".to_string(),
+ "end".to_string(),
+ ]);
+ lines.join("\n")
+}
+
+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ let from = file.parent().context("file has no folder")?;
+ let (_, lib) = backend::Lang::Ruby.artifact(&port.ext);
+ let rel = forward_slashes(&relative(from, &ctx.lib_dir().join(lib)));
+ let block = shim(port, &rel);
+ let patched = if port.module == "__main__" {
+ backend::insert_marked(&text, "#", &port.id, &block, main_guard)
+ } else {
+ backend::append_marked(&text, "#", &port.id, &block)
+ };
+ fs::write(&file, patched).with_context(|| format!("writing {}", port.file))
+}
+
+pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ fs::write(&file, backend::strip_marked(&text, "#", &port.id)).with_context(|| format!("writing {}", port.file))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ruby_defaults_become_json() {
+ assert_eq!(default_json("2").as_deref(), Some("2"));
+ assert_eq!(default_json("1_000").as_deref(), Some("1000"));
+ assert_eq!(default_json("nil").as_deref(), Some("null"));
+ assert_eq!(default_json("'a'").as_deref(), Some("\"a\""));
+ assert_eq!(default_json("[]").as_deref(), Some("[]"));
+ assert_eq!(default_json("SOME_CONST"), None);
+ assert!(is_ruby("ruby") && is_ruby("C:\\Ruby40-x64\\bin\\ruby.exe") && !is_ruby("rubocop"));
+ }
+}
diff --git a/src/ruby/recorder.rb b/src/ruby/recorder.rb
new file mode 100644
index 0000000..8993399
--- /dev/null
+++ b/src/ruby/recorder.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+# Shared value helpers for fast-anything's Ruby side, and the call recorder
+# (preloaded with "ruby -r" when FAST_ANYTHING_RECORD_OUT is set). Not meant to be used by hand.
+require "json"
+
+module FastAnything
+ class Unsupported < StandardError; end
+
+ module_function
+
+ def enc(v)
+ case v
+ when nil, true, false, Integer then v
+ when Float then v.finite? ? v : { "$float" => v.to_s }
+ when String
+ s = v.encoding == Encoding::UTF_8 ? v : v.encode(Encoding::UTF_8)
+ raise Unsupported, "binary String" unless s.valid_encoding?
+ s
+ when Array then v.map { |x| enc(x) }
+ when Hash
+ raise Unsupported, "Hash with non-String keys" unless v.keys.all?(String)
+ { "$hash" => v.map { |k, x| [k, enc(x)] } }
+ when Symbol then raise Unsupported, "Symbol"
+ else raise Unsupported, v.class.name
+ end
+ rescue EncodingError
+ raise Unsupported, "binary String"
+ end
+
+ def dec(v)
+ case v
+ when Array then v.map { |x| dec(x) }
+ when Hash
+ tag, x = v.first
+ case tag
+ when "$float" then { "NaN" => Float::NAN, "Infinity" => Float::INFINITY, "-Infinity" => -Float::INFINITY }.fetch(x)
+ when "$hash" then x.to_h { |k, e| [k, dec(e)] }
+ else raise "unknown tag #{tag}"
+ end
+ else v
+ end
+ end
+
+ def same(a, b)
+ if a.is_a?(Float) || b.is_a?(Float)
+ return false unless a.is_a?(Float) && b.is_a?(Float)
+ return a.nan? && b.nan? if a.nan? || b.nan?
+ return a == b || (a - b).abs <= [1e-12, 1e-9 * [a.abs, b.abs].max].max
+ end
+ return a.length == b.length && a.zip(b).all? { |x, y| same(x, y) } if a.is_a?(Array) && b.is_a?(Array)
+ return a.keys.sort == b.keys.sort && a.all? { |k, x| same(x, b[k]) } if a.is_a?(Hash) && b.is_a?(Hash)
+
+ a.class == b.class && a == b
+ end
+end
+
+if ENV["FAST_ANYTHING_RECORD_OUT"]
+ module FastAnything
+ @kept = []
+ @calls = 0
+ @skipped = 0
+ @unsupported = {}
+ @limit = Integer(ENV.fetch("FAST_ANYTHING_RECORD_LIMIT", "500"))
+ @rng = Random.new(0xFA57)
+
+ class << self
+ attr_reader :kept
+
+ def store(slot, c)
+ if @kept.length < @limit then @kept << c else @kept[slot % @limit] = c end
+ end
+
+ def note(e)
+ @skipped += 1
+ @unsupported[e.message] = true
+ end
+
+ def record(original, receiver, args, blk)
+ @calls += 1
+ slot = @kept.length < @limit ? @kept.length : @rng.rand(@calls)
+ c = nil
+ if slot < @limit
+ begin
+ c = { "args" => enc(args) } # before the call, in case it mutates its arguments
+ rescue Unsupported => e
+ note(e)
+ end
+ end
+ begin
+ result = original.bind_call(receiver, *args, &blk)
+ rescue StandardError => e
+ if c
+ c["raises"] = e.class.name
+ store(slot, c)
+ end
+ raise
+ end
+ if c
+ begin
+ c["result"] = enc(result)
+ store(slot, c)
+ rescue Unsupported => e
+ note(e)
+ end
+ end
+ result
+ end
+
+ def save
+ File.write(ENV.fetch("FAST_ANYTHING_RECORD_OUT"), @kept.map { |c| JSON.generate(c) + "\n" }.join)
+ File.write(ENV.fetch("FAST_ANYTHING_RECORD_META"),
+ JSON.generate({ "calls" => @calls, "kept" => @kept.length, "skipped" => @skipped, "unsupported" => @unsupported.keys }))
+ end
+ end
+ end
+
+ $__fast_anything_wrap = lambda do |owner, name|
+ original = owner.instance_method(name)
+ was_private = owner.private_method_defined?(name)
+ owner.send(:define_method, name) { |*args, &blk| FastAnything.record(original, self, args, blk) }
+ owner.send(:private, name) if was_private
+ end
+
+ at_exit { FastAnything.save }
+end
diff --git a/src/ruby/runner.rb b/src/ruby/runner.rb
new file mode 100644
index 0000000..00bfd16
--- /dev/null
+++ b/src/ruby/runner.rb
@@ -0,0 +1,354 @@
+# frozen_string_literal: true
+
+# Ruby side of fast-anything. The CLI copies this file to <project>/.fast/runner.rb and runs
+# ruby runner.rb <mode> <job.json> -- <the app's ruby arguments>
+# Modes: profile, verify. Not meant to be run by hand.
+require "json"
+require "prism"
+require_relative "recorder"
+
+SKIP_DIRS = %w[.fast .git vendor node_modules].freeze
+IO_CALLS = %i[puts print p pp gets printf putc open system exec spawn sleep warn require require_relative load exit abort fork trap].freeze
+IO_RECEIVERS = %w[File IO Dir STDIN STDOUT STDERR $stdout $stderr $stdin Kernel Net::HTTP Socket TCPSocket Process FileUtils Open3].freeze
+NONDET_CALLS = %i[rand srand].freeze
+NONDET_RECEIVERS = %w[Random Time SecureRandom Date DateTime].freeze
+GUARDS = ["__FILE__==$0", "$0==__FILE__", "__FILE__==$PROGRAM_NAME", "$PROGRAM_NAME==__FILE__"].freeze
+
+def parse_target(argv)
+ args = argv.dup
+ while args.first&.start_with?("-")
+ flag = args.shift
+ args.shift if %w[-r -I -C].include?(flag)
+ end
+ abort "fast-anything: give the app as 'ruby script.rb ...'" if args.empty?
+ [File.expand_path(args.shift), args]
+end
+
+def run_target(script, rest)
+ $0 = script # so "if __FILE__ == $0" runs, as in a normal start
+ ARGV.replace(rest)
+ load script
+rescue SystemExit => e
+ raise unless e.success?
+end
+
+# ------------------------------------------------------------------ static analysis
+
+def parsed(path)
+ @parsed ||= {}
+ return @parsed[path] if @parsed.key?(path)
+
+ result = Prism.parse_file(path)
+ defs = []
+ guard = nil
+ walk = lambda do |node, owner, in_def|
+ node.compact_child_nodes.each do |child|
+ case child
+ when Prism::DefNode
+ kind, own =
+ if in_def then ["nested", nil]
+ elsif child.receiver.is_a?(Prism::SelfNode) then owner ? ["singleton", "#{owner}.singleton_class"] : %w[object Object]
+ elsif owner&.end_with?(".singleton_class") then ["singleton", owner]
+ elsif owner.nil? then %w[object Object]
+ else ["method", owner]
+ end
+ defs << { node: child, kind: kind, owner: own }
+ walk.call(child, owner, true)
+ when Prism::ModuleNode, Prism::ClassNode
+ name = child.constant_path.slice
+ walk.call(child, owner ? "#{owner}::#{name}" : name, in_def)
+ when Prism::SingletonClassNode
+ walk.call(child, owner ? "#{owner}.singleton_class" : "Object", in_def)
+ when Prism::IfNode
+ guard ||= child.location.start_line if owner.nil? && !in_def && GUARDS.include?(child.predicate.slice.delete(" "))
+ walk.call(child, owner, in_def)
+ else
+ walk.call(child, owner, in_def)
+ end
+ end
+ end
+ walk.call(result.value, nil, false)
+ @parsed[path] = { src: File.read(path, encoding: "UTF-8"), defs: defs, guard: guard }
+rescue StandardError
+ @parsed[path] = nil
+end
+
+def each_node(node, &block)
+ return unless node
+
+ yield node
+ node.compact_child_nodes.each { |c| each_node(c, &block) }
+end
+
+def describe(path, line, name, entry, root)
+ info = parsed(path) or return nil
+ d = info[:defs]
+ .select { |x| x[:node].name == name.to_sym && x[:node].location.start_line <= line && line <= x[:node].location.end_line }
+ .min_by { |x| x[:node].location.end_line - x[:node].location.start_line }
+ return nil unless d
+
+ node = d[:node]
+ blockers = []
+ warnings = []
+ factor = 0.9
+ warnings << "no types in Ruby, types are inferred from recorded calls"
+ rel = path.delete_prefix(root + "/")
+ is_entry = entry && File.expand_path(entry) == File.expand_path(path)
+ mod = is_entry ? "__main__" : rel.sub(/\.rb\z/, "").tr("/", ".")
+ if is_entry && info[:guard].nil?
+ blockers << "lives in the entry script, which runs on load: put that code under if __FILE__ == $0"
+ elsif is_entry && node.location.start_line > info[:guard]
+ blockers << "defined inside the if __FILE__ == $0 block"
+ end
+ blockers << "instance method (module functions and top-level methods only for now)" if d[:kind] == "method"
+ blockers << "nested method" if d[:kind] == "nested"
+
+ params = []
+ if (ps = node.parameters)
+ blockers << "takes keyword, block or splat arguments" if ps.keywords.any? || ps.keyword_rest || ps.block || ps.rest || ps.posts.any?
+ ps.requireds.each { |r| params << { "name" => r.respond_to?(:name) ? r.name.to_s : r.slice, "annotation" => nil, "default" => nil } }
+ ps.optionals.each { |o| params << { "name" => o.name.to_s, "annotation" => nil, "default" => o.value.slice } }
+ end
+
+ siblings = info[:defs].select { |x| x[:owner] == d[:owner] && x[:kind] != "nested" }.map { |x| x[:node].name }
+ owner_base = d[:owner]&.delete_suffix(".singleton_class")
+ io = []
+ nondet = []
+ helpers = []
+ each_node(node.body) do |n|
+ case n
+ when Prism::CallNode
+ recv = n.receiver&.slice
+ io << n.name.to_s if recv.nil? && IO_CALLS.include?(n.name)
+ io << "#{recv}.#{n.name}" if recv && IO_RECEIVERS.include?(recv)
+ nondet << (recv ? "#{recv}.#{n.name}" : n.name.to_s) if (recv.nil? && NONDET_CALLS.include?(n.name)) || NONDET_RECEIVERS.include?(recv)
+ local = recv.nil? || recv == "self" || recv == owner_base
+ helpers << n.name.to_s if local && siblings.include?(n.name) && n.name != node.name
+ when Prism::XStringNode, Prism::InterpolatedXStringNode then io << "backticks"
+ when Prism::YieldNode then blockers << "yields to a block"
+ when Prism::SuperNode, Prism::ForwardingSuperNode then blockers << "calls super"
+ else
+ kind = n.class.name.split("::").last
+ blockers << "writes instance, class or global variables" if kind.match?(/\A(Instance|Class|Global)Variable.*Write/)
+ end
+ end
+ blockers << "does I/O: #{io.uniq.first(3).join(", ")}" if io.any?
+ blockers << "not deterministic: #{nondet.uniq.first(3).join(", ")}" if nondet.any?
+ helpers.uniq!
+ warnings << "calls #{helpers.first(3).join(", ")}, they get ported together with it" if helpers.any?
+ blockers.uniq!
+
+ lines = info[:src].lines
+ {
+ "qualname" => name.to_s, "module" => mod, "kind" => "function", "line" => node.location.start_line, "end_line" => node.location.end_line,
+ "params" => params, "returns" => nil, "blockers" => blockers, "warnings" => warnings,
+ "portability" => blockers.empty? ? factor : 0.0, "calls" => helpers, "owner" => d[:owner],
+ "source" => lines[(node.location.start_line - 1)...node.location.end_line].join.rstrip,
+ }
+end
+
+def project_relative(root, path)
+ return nil unless path.start_with?(root + "/")
+
+ rel = path.delete_prefix(root + "/")
+ return nil if rel.split("/")[0...-1].any? { |p| SKIP_DIRS.include?(p) }
+
+ rel
+end
+
+# ------------------------------------------------------------------ modes
+
+def cmd_profile(job, argv)
+ script, rest = parse_target(argv)
+ root = File.expand_path(job["root"])
+ stats = Hash.new { |h, k| h[k] = [0, 0.0, 0.0] } # calls, self, cumulative
+ first_line = {}
+ active = Hash.new(0)
+ stack = []
+ clock = Process::CLOCK_MONOTONIC
+ tracer = TracePoint.new(:call, :return) do |t|
+ path = t.path
+ next unless path.start_with?(root)
+
+ if t.event == :call
+ key = [path, t.method_id]
+ first_line[key] ||= t.lineno
+ active[key] += 1
+ stack << [key, Process.clock_gettime(clock), 0.0]
+ elsif (frame = stack.pop)
+ key, started, children = frame
+ took = Process.clock_gettime(clock) - started
+ s = stats[key]
+ s[0] += 1
+ s[1] += took - children
+ active[key] -= 1
+ s[2] += took if active[key].zero?
+ stack.last[2] += took if stack.last
+ end
+ end
+ started = Process.clock_gettime(clock)
+ tracer.enable { run_target(script, rest) }
+ wall = Process.clock_gettime(clock) - started
+
+ rows = stats.filter_map do |(path, name), (calls, own, cum)|
+ rel = project_relative(root, path) or next
+ [path, rel, first_line[[path, name]], name, calls, own, cum]
+ end
+ functions = rows.sort_by { |r| -r[6] }.first(40).filter_map do |path, rel, line, name, calls, own, cum|
+ info = describe(path, line, name, script, root) or next
+ info.merge("file" => rel, "name" => name.to_s, "ncalls" => calls, "tottime" => own, "cumtime" => cum)
+ end
+ File.write(job["out"], JSON.generate({ "wall" => wall, "base" => ".", "functions" => functions }))
+end
+
+def bridge(path)
+ require "fiddle"
+ lib = Fiddle.dlopen(path)
+ call = Fiddle::Function.new(lib["fa_call"], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T, Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP)
+ free = Fiddle::Function.new(lib["fa_free"], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T], Fiddle::TYPE_VOID)
+ lambda do |*args|
+ input = JSON.generate(args)
+ size = Fiddle::Pointer.malloc(Fiddle::SIZEOF_SIZE_T, Fiddle::RUBY_FREE)
+ out = call.call(input, input.bytesize, size)
+ len = size[0, Fiddle::SIZEOF_SIZE_T].unpack1("J")
+ text = out[0, len].force_encoding(Encoding::UTF_8)
+ free.call(out, len)
+ reply = JSON.parse(text)
+ raise reply["error"] if reply.key?("error")
+
+ reply["ok"]
+ end
+end
+
+SLICE_LENGTHS = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55].freeze
+
+def variants(value, rng)
+ return [] unless (value.is_a?(Array) || value.is_a?(String)) && value.length >= 2
+
+ SLICE_LENGTHS.select { |n| n < value.length }.flat_map do |n|
+ Array.new(n < 2 ? 1 : 3) { value[rng.rand(value.length - n + 1), n] }
+ end
+end
+
+def derive(original, cases, budget, limit)
+ rng = Random.new(0xFA57)
+ derived = []
+ seen = {}
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ cases.each do |c|
+ next if c.key?("raises")
+
+ args = FastAnything.dec(c["args"])
+ args.each_with_index do |arg, i|
+ variants(arg, rng).each do |smaller|
+ return derived if derived.length >= limit || Process.clock_gettime(Process::CLOCK_MONOTONIC) - started > budget
+
+ next_args = args.dup
+ next_args[i] = smaller
+ begin
+ encoded = { "args" => FastAnything.enc(next_args) }
+ key = JSON.generate(encoded)
+ next if seen[key]
+
+ seen[key] = true
+ encoded["result"] = FastAnything.enc(original.call(*Marshal.load(Marshal.dump(next_args))))
+ rescue StandardError
+ next # outside the function's domain: not a fair test
+ end
+ encoded["derived"] = true
+ derived << encoded
+ end
+ end
+ end
+ derived
+end
+
+def best_pass(fn, calls, budget)
+ best = Float::INFINITY
+ spent = 0.0
+ passes = 0
+ while passes < 3 || (spent < budget && passes < 2000)
+ t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ calls.each do |args|
+ fn.call(*args)
+ rescue StandardError
+ nil
+ end
+ took = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t
+ best = [best, took].min
+ spent += took
+ passes += 1
+ end
+ best
+end
+
+def show(v, limit = 160)
+ s = v.inspect
+ s.length <= limit ? s : "#{s[0, limit - 1]}…"
+end
+
+def cmd_verify(job, _argv)
+ ENV["FAST_ANYTHING_DISABLE"] = "1"
+ fast = bridge(job["lib"])
+ $0 = "fast-anything-verify" # the entry script's "if __FILE__ == $0" block must not run
+ load job["module_file"]
+ receiver = job["owner"] == "Object" ? Object.new : Object.const_get(job["owner"].delete_suffix(".singleton_class"))
+ owner = job["owner"] == "Object" ? Object : receiver.singleton_class
+ method = owner.instance_method(job["func"])
+ original = ->(*args) { method.bind_call(receiver, *args) }
+
+ cases = File.readlines(job["cases"], chomp: true).reject(&:empty?).map { |l| JSON.parse(l) }
+ recorded = cases.length
+ derived = derive(original, cases, job.fetch("derive_budget", 3.0), job.fetch("derive_limit", 200))
+ cases += derived
+ report = { "total" => cases.length, "derived" => derived.length, "passed" => 0, "failed" => 0, "failures" => [] }
+ calls = []
+ cases.each_with_index do |c, i|
+ args = FastAnything.dec(c["args"])
+ calls << args
+ err = nil
+ begin
+ got = fast.call(*args)
+ rescue StandardError => e
+ err = e
+ end
+ if c.key?("raises")
+ ok = !err.nil?
+ expected = "raises #{c["raises"]}"
+ else
+ want = FastAnything.dec(c["result"])
+ ok = err.nil? && FastAnything.same(want, got)
+ expected = show(want)
+ end
+ if ok
+ report["passed"] += 1
+ next
+ end
+ report["failed"] += 1
+ next unless report["failures"].length < 8
+
+ report["failures"] << {
+ "case" => i,
+ "call" => "#{c["derived"] ? "(derived) " : ""}#{job["func"]}(#{args.map { |a| show(a, 80) }.join(", ")})",
+ "expected" => expected,
+ "got" => err ? "raised #{err.class}: #{show(err.message, 200)}" : show(got),
+ }
+ end
+ if recorded.positive? && report["failed"].zero?
+ calls = calls.first(recorded)
+ rb = best_pass(original, calls, job.fetch("budget", 0.5))
+ rs = best_pass(fast, calls, job.fetch("budget", 0.5))
+ report["micro"] = { "original_ns" => rb / calls.length * 1e9, "rust_ns" => rs / calls.length * 1e9, "speedup" => rs.positive? ? rb / rs : 0 }
+ end
+ File.write(job["out"], JSON.generate(report))
+end
+
+mode, job_path, *rest = ARGV
+rest.shift if rest.first == "--"
+job = JSON.parse(File.read(job_path))
+ARGV.clear
+case mode
+when "profile" then cmd_profile(job, rest)
+when "verify" then cmd_verify(job, rest)
+else abort "unknown mode #{mode}"
+end
diff --git a/src/show.rs b/src/show.rs
new file mode 100644
index 0000000..5d96c29
--- /dev/null
+++ b/src/show.rs
@@ -0,0 +1,201 @@
+//! How results look in the terminal.
+
+use crate::bench::BenchResult;
+use crate::pipeline::{PortOut, ScanOut};
+use crate::report::ReportOut;
+use crate::state::{Ctx, Verify};
+use crate::ui::{self, bold, dim, green, red, rust, yellow};
+use crate::util::{nanos, secs, thousands, times};
+
+fn bar(share: f64, width: usize) -> String {
+ const PARTS: [char; 8] = ['▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'];
+ let eighths = (share.clamp(0.0, 1.0) * (width * 8) as f64).round() as usize;
+ let mut s = "█".repeat(eighths / 8);
+ if !eighths.is_multiple_of(8) {
+ s.push(PARTS[eighths % 8 - 1]);
+ }
+ format!("{s:<width$}")
+}
+
+fn pad(s: &str, n: usize) -> String {
+ let len = s.chars().count();
+ if len >= n {
+ format!("{}…", s.chars().take(n - 1).collect::<String>())
+ } else {
+ format!("{s}{}", " ".repeat(n - len))
+ }
+}
+
+pub fn next(cmd: &str) {
+ ui::line(format!(" {} {}", dim("→"), bold(cmd)));
+}
+
+pub fn scan(s: &ScanOut) {
+ ui::ok(format!("{} ran in {}", bold(s.command.join(" ")), secs(s.wall)));
+ ui::line("");
+ if s.hotspots.is_empty() {
+ ui::line(" No functions from your own code showed up. Is the app doing its work in a library?");
+ return;
+ }
+ ui::line(dim(format!(" # {} {:<16}{:>11} verdict", pad("function", 30), "time", "calls")));
+ for (i, h) in s.hotspots.iter().take(10).enumerate() {
+ let verdict = if let Some(by) = &h.covered_by {
+ dim(format!("↳ ported inside {}", by.rsplit(['.', ':']).next().unwrap_or(by)))
+ } else if h.worth_it() {
+ green("✓ port it")
+ } else if h.portable() {
+ dim("· too small to matter")
+ } else {
+ dim(format!("✗ {}", h.blockers[0]))
+ };
+ let row = format!(
+ " {:>2} {} {} {:>5.1}%{:>11} {verdict}",
+ i + 1,
+ pad(&h.id, 30),
+ rust(bar(h.share, 9)),
+ h.share * 100.0,
+ if h.ncalls == 0 { "-".to_string() } else { thousands(h.ncalls) }
+ );
+ ui::line(if h.worth_it() { row } else { dim(row) });
+ if h.worth_it() {
+ for w in &h.warnings {
+ ui::line(format!("{}{}", " ".repeat(36), yellow(format!("! {w}"))));
+ }
+ }
+ }
+ ui::line("");
+ match s.hotspots.iter().find(|h| h.worth_it()) {
+ Some(h) => next(&format!("fast-anything port {}", h.id)),
+ None => {
+ ui::line(" Nothing portable takes a real share of the run yet. The ✗ reasons above say what's in the way.")
+ }
+ }
+}
+
+pub fn port(p: &PortOut, show_next: bool) {
+ ui::ok(format!(
+ "recorded {} real call{} to {} (of {} made){}",
+ thousands(p.recorded as u64),
+ if p.recorded == 1 { "" } else { "s" },
+ bold(&p.id),
+ thousands(p.calls_seen),
+ if p.skipped > 0 { format!(", skipped {} with non-plain data", p.skipped) } else { String::new() }
+ ));
+ ui::ok(format!("Rust crate ready: {}", p.crate_dir.display()));
+ if show_next {
+ let file = p.lib_rs.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
+ ui::line(format!(
+ " Have your coding agent follow {} and write {}, then:",
+ bold("TASK.md"),
+ bold(format!("src/{file}"))
+ ));
+ next(&format!("fast-anything verify {}", p.id));
+ }
+}
+
+pub fn verify(id: &str, v: &Verify) {
+ if let Some(log) = &v.build_log {
+ ui::error(format!("{} doesn't compile yet:", bold(id)));
+ for line in log.lines().take(25) {
+ ui::line(format!(" {}", dim(line)));
+ }
+ return;
+ }
+ if v.ok() {
+ if v.derived > 0 {
+ ui::ok(format!(
+ "{}/{} calls give the same result {}",
+ v.passed,
+ v.total,
+ dim(format!("({} recorded + {} derived)", v.total - v.derived, v.derived))
+ ));
+ } else {
+ ui::ok(format!("{}/{} recorded calls give the same result", v.passed, v.total));
+ }
+ if let Some(m) = v.micro {
+ ui::ok(format!(
+ "{} per call: {} in {}, {} in Rust: {}",
+ bold(id),
+ nanos(m.original_ns),
+ v.lang.label(),
+ nanos(m.rust_ns),
+ rust(bold(format!("{} faster", times(m.speedup))))
+ ));
+ }
+ return;
+ }
+ ui::error(format!("{}/{} calls don't match", v.failed, v.total));
+ for f in v.failures.iter().take(5) {
+ ui::line(format!(" {}", f.call));
+ ui::line(format!(" expected {}", green(&f.expected)));
+ ui::line(format!(" got {}", red(&f.got)));
+ }
+}
+
+pub fn bench(b: &BenchResult) {
+ let cmd = b.command.join(" ");
+ ui::line("");
+ ui::line(format!(" {} {} {}", pad(b.lang.label(), 11), dim(bar(1.0, 24)), secs(b.before.median)));
+ ui::line(format!(
+ " {} {} {}",
+ pad("Rust", 11),
+ rust(bar(b.after.median / b.before.median.max(1e-12), 24)),
+ secs(b.after.median)
+ ));
+ ui::line("");
+ ui::ok(format!(
+ "{} is {} end to end {}",
+ bold(cmd),
+ rust(bold(format!("{} faster", times(b.speedup)))),
+ dim(format!("(median of {}, ±{})", b.runs, secs(b.after.stddev.max(b.before.stddev))))
+ ));
+}
+
+pub fn report(r: &ReportOut) {
+ ui::ok(format!("report: {}", r.markdown.display()));
+ ui::ok(format!("share card: {}", r.svg.display()));
+}
+
+pub fn status(ctx: &Ctx) {
+ let s = &ctx.state;
+ if s.command.is_empty() {
+ ui::line(" No scan yet.");
+ next("fast-anything scan -- python your_app.py");
+ return;
+ }
+ ui::line(format!(" app: {} profiled run: {}", bold(s.command.join(" ")), secs(s.wall)));
+ if s.ports.is_empty() {
+ ui::line(" Nothing ported yet.");
+ if let Some(h) = s.hotspots.iter().find(|h| h.worth_it()) {
+ next(&format!("fast-anything port {}", h.id));
+ }
+ return;
+ }
+ ui::line("");
+ for p in s.ports.values() {
+ let (label, paint): (&str, fn(String) -> String) = match (&p.verify, p.enabled) {
+ (_, true) => ("● on (Rust)", |s| green(s)),
+ (Some(v), false) if v.ok() => ("○ verified, off", |s| yellow(s)),
+ (Some(v), false) if !v.built => ("✗ doesn't compile", |s| red(s)),
+ (Some(_), false) => ("✗ mismatches", |s| red(s)),
+ (None, false) => ("○ waiting for the Rust", |s| dim(s)),
+ };
+ let state = paint(pad(label, 26));
+ let speed = p
+ .verify
+ .as_ref()
+ .and_then(|v| v.micro)
+ .map(|m| format!("{} per call", times(m.speedup)))
+ .unwrap_or_default();
+ ui::line(format!(" {} {} {}", pad(&p.id, 32), state, dim(speed)));
+ }
+ if let Some(b) = &s.bench {
+ ui::line("");
+ ui::line(format!(
+ " last bench: {} → {} ({})",
+ secs(b.before.median),
+ secs(b.after.median),
+ rust(bold(times(b.speedup)))
+ ));
+ }
+}
diff --git a/src/state.rs b/src/state.rs
new file mode 100644
index 0000000..5ecdc78
--- /dev/null
+++ b/src/state.rs
@@ -0,0 +1,164 @@
+//! Everything fast-anything knows about a project, kept in <project>/.fast/state.json.
+
+use crate::backend::Lang;
+use crate::bench::BenchResult;
+use crate::hotspot::Hotspot;
+use crate::util;
+use anyhow::{Context, Result, bail, ensure};
+use serde::{Deserialize, Serialize};
+use std::collections::BTreeMap;
+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";
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct State {
+ pub version: u32,
+ /// How the app is run, e.g. ["python", "app.py"].
+ pub command: Vec<String>,
+ pub lang: Lang,
+ /// Absolute path of the interpreter (python, node).
+ #[serde(alias = "python")]
+ pub runtime: Option<String>,
+ /// Folder Python imports the app's modules from, relative to the project.
+ pub base: String,
+ pub wall: f64,
+ pub hotspots: Vec<Hotspot>,
+ pub ports: BTreeMap<String, Port>,
+ pub bench: Option<BenchResult>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Port {
+ pub id: String,
+ pub file: String,
+ pub module: String,
+ pub func: String,
+ /// Name of the compiled extension module.
+ pub ext: String,
+ pub crate_dir: String,
+ pub recorded: usize,
+ pub calls_seen: u64,
+ pub verify: Option<Verify>,
+ pub enabled: bool,
+ #[serde(default)]
+ pub lang: Lang,
+ #[serde(default)]
+ pub owner: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Verify {
+ pub built: bool,
+ pub build_log: Option<String>,
+ pub total: usize,
+ /// Of total: extra cases made by shrinking recorded inputs, answered by the original.
+ pub derived: usize,
+ pub passed: usize,
+ pub failed: usize,
+ pub failures: Vec<Failure>,
+ pub micro: Option<Micro>,
+ pub lang: Lang,
+}
+
+impl Verify {
+ pub fn ok(&self) -> bool {
+ self.built && self.total > 0 && self.failed == 0
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Failure {
+ pub case: usize,
+ pub call: String,
+ pub expected: String,
+ pub got: String,
+}
+
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Micro {
+ /// Per call in the original language.
+ #[serde(alias = "python_ns")]
+ pub original_ns: f64,
+ pub rust_ns: f64,
+ pub speedup: f64,
+}
+
+pub struct Ctx {
+ pub root: PathBuf,
+ pub fast: PathBuf,
+ pub state: State,
+}
+
+impl Ctx {
+ pub fn open(root: &Path) -> Result<Ctx> {
+ let root = util::absolute(root);
+ ensure!(root.is_dir(), "{} isn't a folder", root.display());
+ let fast = root.join(".fast");
+ fs::create_dir_all(&fast).context("creating .fast/")?;
+ let gitignore = fast.join(".gitignore");
+ if !gitignore.exists() {
+ fs::write(&gitignore, GITIGNORE)?;
+ }
+ let path = fast.join("state.json");
+ let state = if path.exists() {
+ serde_json::from_str(&fs::read_to_string(&path)?).context("reading .fast/state.json")?
+ } else {
+ State { version: 1, ..State::default() }
+ };
+ Ok(Ctx { root, fast, state })
+ }
+
+ pub fn save(&self) -> Result<()> {
+ let tmp = self.fast.join("state.json.tmp");
+ fs::write(&tmp, serde_json::to_string_pretty(&self.state)?)?;
+ fs::rename(&tmp, self.fast.join("state.json")).context("saving .fast/state.json")
+ }
+
+ pub fn runtime(&self) -> Result<&str> {
+ self.state.runtime.as_deref().context("no scan yet: run fast-anything scan -- python your_app.py (or node)")
+ }
+
+ pub fn lib_dir(&self) -> PathBuf {
+ self.fast.join("lib")
+ }
+
+ pub fn crate_dir(&self, port: &Port) -> PathBuf {
+ self.root.join(port.crate_dir.replace('/', std::path::MAIN_SEPARATOR_STR))
+ }
+
+ pub fn base_dir(&self) -> PathBuf {
+ self.root.join(if self.state.base.is_empty() { "." } else { &self.state.base })
+ }
+
+ /// Accepts a full id, a bare function name, or nothing when there's exactly one port.
+ pub fn resolve_port(&self, id: Option<&str>) -> Result<String> {
+ let ports = &self.state.ports;
+ let names = || ports.keys().cloned().collect::<Vec<_>>().join(", ");
+ match id {
+ None => match ports.len() {
+ 0 => bail!("nothing ported yet: run fast-anything port"),
+ 1 => Ok(ports.keys().next().cloned().unwrap_or_default()),
+ _ => bail!("which one? {}", names()),
+ },
+ Some(id) if ports.contains_key(id) => Ok(id.to_string()),
+ Some(id) => {
+ let suffix = format!(".{id}");
+ let hits: Vec<&String> =
+ ports.values().filter(|p| p.func == id || p.id.ends_with(&suffix)).map(|p| &p.id).collect();
+ match hits.as_slice() {
+ [one] => Ok((*one).clone()),
+ [] if ports.is_empty() => bail!("nothing ported yet: run fast-anything port {id}"),
+ [] => bail!("no port called {id} (have: {})", names()),
+ _ => bail!("{id} is ambiguous: {}", names()),
+ }
+ }
+ }
+ }
+}
diff --git a/src/ui.rs b/src/ui.rs
new file mode 100644
index 0000000..8571a31
--- /dev/null
+++ b/src/ui.rs
@@ -0,0 +1,72 @@
+//! Terminal output. Silent in MCP mode, where stdout belongs to the protocol.
+
+use std::fmt::Display;
+use std::io::IsTerminal;
+use std::sync::OnceLock;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+static QUIET: AtomicBool = AtomicBool::new(false);
+static COLOR: OnceLock<bool> = OnceLock::new();
+
+pub fn set_quiet(quiet: bool) {
+ QUIET.store(quiet, Ordering::Relaxed);
+}
+
+pub fn quiet() -> bool {
+ QUIET.load(Ordering::Relaxed)
+}
+
+fn color() -> bool {
+ *COLOR.get_or_init(|| std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal())
+}
+
+fn paint(code: &str, s: impl Display) -> String {
+ if color() { format!("\x1b[{code}m{s}\x1b[0m") } else { s.to_string() }
+}
+
+pub fn bold(s: impl Display) -> String {
+ paint("1", s)
+}
+pub fn dim(s: impl Display) -> String {
+ paint("2", s)
+}
+pub fn green(s: impl Display) -> String {
+ paint("32", s)
+}
+pub fn red(s: impl Display) -> String {
+ paint("31", s)
+}
+pub fn yellow(s: impl Display) -> String {
+ paint("33", s)
+}
+pub fn rust(s: impl Display) -> String {
+ paint("38;5;208", s)
+}
+
+pub fn line(s: impl Display) {
+ if !quiet() {
+ println!("{s}");
+ }
+}
+
+pub fn step(s: impl Display) {
+ line(format!("{} {s}", rust("▸")));
+}
+
+pub fn ok(s: impl Display) {
+ line(format!("{} {s}", green("✓")));
+}
+
+pub fn warn(s: impl Display) {
+ if !quiet() {
+ eprintln!("{} {s}", yellow("!"));
+ }
+}
+
+pub fn error(s: impl Display) {
+ eprintln!("{} {s}", red("✗"));
+}
+
+pub fn banner() {
+ line(format!("{} {}", rust(bold("⚡ fast-anything")), dim(concat!("v", env!("CARGO_PKG_VERSION")))));
+}
diff --git a/src/util.rs b/src/util.rs
new file mode 100644
index 0000000..32556e2
--- /dev/null
+++ b/src/util.rs
@@ -0,0 +1,105 @@
+//! Small helpers: paths, processes, number formatting.
+
+use anyhow::{Context, Result};
+use std::path::{Component, Path, PathBuf};
+use std::process::{Command, Output};
+
+pub fn absolute(p: &Path) -> PathBuf {
+ std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf())
+}
+
+/// Path from directory from to to, both absolute.
+pub fn relative(from: &Path, to: &Path) -> PathBuf {
+ let a: Vec<Component> = from.components().collect();
+ let b: Vec<Component> = to.components().collect();
+ let common = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
+ let mut out = PathBuf::new();
+ for _ in common..a.len() {
+ out.push("..");
+ }
+ for c in &b[common..] {
+ out.push(c);
+ }
+ out
+}
+
+pub fn forward_slashes(p: &Path) -> String {
+ p.to_string_lossy().replace('\\', "/")
+}
+
+/// A name safe for Rust crates and Python modules.
+pub fn slug(id: &str) -> String {
+ id.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect()
+}
+
+pub fn output(cmd: &mut Command, what: &str) -> Result<Output> {
+ cmd.output().with_context(|| format!("couldn't start {what} ({})", cmd.get_program().to_string_lossy()))
+}
+
+pub fn combined(out: &Output) -> String {
+ format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr))
+}
+
+pub fn tail(text: &str, n: usize) -> String {
+ let lines: Vec<&str> = text.trim_end().lines().collect();
+ lines[lines.len().saturating_sub(n)..].join("\n")
+}
+
+pub fn secs(s: f64) -> String {
+ if s >= 1.0 {
+ format!("{s:.2}s")
+ } else if s >= 1e-3 {
+ format!("{:.0}ms", s * 1e3)
+ } else {
+ format!("{:.0}µs", s * 1e6)
+ }
+}
+
+pub fn nanos(ns: f64) -> String {
+ if ns < 1e3 {
+ format!("{ns:.0}ns")
+ } else if ns < 1e6 {
+ format!("{:.1}µs", ns / 1e3)
+ } else {
+ format!("{:.1}ms", ns / 1e6)
+ }
+}
+
+pub fn times(x: f64) -> String {
+ if x >= 10.0 { format!("{x:.0}×") } else { format!("{x:.1}×") }
+}
+
+pub fn thousands(n: u64) -> String {
+ let s = n.to_string();
+ let mut out = String::new();
+ for (i, c) in s.chars().enumerate() {
+ if i > 0 && (s.len() - i).is_multiple_of(3) {
+ out.push(',');
+ }
+ out.push(c);
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn relative_paths() {
+ let r = relative(Path::new("/a/b/c"), Path::new("/a/.fast/lib"));
+ assert_eq!(forward_slashes(&r), "../../.fast/lib");
+ assert_eq!(forward_slashes(&relative(Path::new("/a"), Path::new("/a/x"))), "x");
+ }
+
+ #[test]
+ fn formatting() {
+ assert_eq!(thousands(1234567), "1,234,567");
+ assert_eq!(thousands(12), "12");
+ assert_eq!(times(87.4), "87×");
+ assert_eq!(times(3.21), "3.2×");
+ assert_eq!(slug("text.utils.Lev-1"), "text_utils_lev_1");
+ assert_eq!(nanos(350.0), "350ns");
+ assert_eq!(secs(0.25), "250ms");
+ }
+}