К основному содержанию
плагин

rust-anything — плагин для Claude Code: Rust-миграция

Плагин rust-anything для Claude Code переносит части приложения на Rust и сверяет поведение с записью оригинала. Работает по шагам.

MIT ★ 7 482 обновлён 2026-11-17

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add erkamyaman/rust-anything
/plugin install rust-anything@rust-anything
Открыть на GitHub

Что делает rust-anything

rust-anything помогает переносить приложение на Rust по частям: сначала профилирует код, затем создаёт мост, записывает поведение исходной версии и сравнивает его с портом. В workflow входят команды profile, bridge, record, diff, bench, shadow и gate. Rust-код пишет агент или разработчик.

Плагин добавляет MCP-сервер и скилл для рабочего процесса миграции. Он подходит для TypeScript/JavaScript, Python, C, Go, Ruby и Java; для связки с исходным кодом используются napi-rs, wasm-bindgen, PyO3 и другие механизмы из проекта. CLI rust-anything должен находиться в PATH, его можно установить командой cargo install rust-anything.

Проверка опирается на записанные сценарии: случаи, которых запись не покрывает, не проверяются. Для установки через маркетплейс Claude Code нужны команды /plugin marketplace add erkamyaman/rust-anything и /plugin install rust-anything@rust-anything.

Какие задачи решает

  • найти горячий участок приложения перед переносом на Rust
  • перенести функцию, модуль или часть сервера по шагам
  • сверить результаты Rust-порта с поведением оригинала
  • сравнить производительность исходной и новой реализации
  • задать условие завершения миграции через проверку

Примеры запросов агенту

  • Профилируй приложение и найди горячий участок для переноса на Rust.
  • Перенеси src/parser/ на Rust и сравни результат с оригиналом.
  • Запиши поведение rust/fuzzy-rs, выполни проверку и замерь производительность.

Как установить rust-anything

Через маркетплейс плагинов

/plugin marketplace add erkamyaman/rust-anything
/plugin install rust-anything@rust-anything

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы о rust-anything

Как установить rust-anything в Claude Code?

Добавить маркетплейс командой /plugin marketplace add erkamyaman/rust-anything, затем установить плагин командой /plugin install rust-anything@rust-anything.

Что делает rust-anything?

Плагин ведёт миграцию приложения на Rust по частям: профилирует исходный код, помогает создать мост, записывает его поведение и сверяет порт с этими записями. В workflow также есть замеры и команда gate для проверки готовности.

Что нужно для работы rust-anything?

Нужен CLI rust-anything в PATH. Его можно установить командой cargo install rust-anything; при установке плагина используются MCP-сервер и скилл.

Исходный текст

SKILL.md · MIT
<p align="center">
  <img src="docs/assets/logo.svg" width="160" height="160" alt="The rust-anything crab, its mouth a code tag">
</p>

<h1 align="center">rust-anything</h1>

<p align="center"><em>Rewrite your whole app in Rust. Keep it working the whole way.</em></p>

<p align="center"><em>CLIs, servers and libraries, piece by piece, checked against the original at every step.</em></p>

<p align="center">
  <a href="https://crates.io/crates/rust-anything"><img src="https://img.shields.io/crates/v/rust-anything?color=E2862A&label=crates.io" alt="crates.io version"></a>
  <a href="https://www.npmjs.com/package/rust-anything"><img src="https://img.shields.io/npm/v/rust-anything?color=E2862A&label=npm" alt="npm version"></a>
  <img src="https://img.shields.io/badge/languages-6-E2862A" alt="6 languages">
  <a href="#works-with"><img src="https://img.shields.io/badge/works%20with-4%20agents-E2862A" alt="Works with 4 agents"></a>
  <a href="https://github.com/erkamyaman/rust-anything/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/erkamyaman/rust-anything/ci.yml?branch=main&label=tests" alt="Tests"></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-E2862A" alt="MIT license"></a>
  <a href="https://github.com/erkamyaman/rust-anything"><img src="https://img.shields.io/github/stars/erkamyaman/rust-anything?style=social" alt="GitHub stars"></a>
</p>

<p align="center">up to 20x faster · 38,251 recorded cases replayed · 0 mismatches · one command</p>

**Rewrite your whole app in Rust, one piece at a time.** rust-anything records what your
TypeScript/JavaScript, Python, C, Go, Ruby or Java app does today, then checks every piece of the
Rust rewrite against that recording before it moves on, until the app is pure Rust. CLIs, HTTP
servers and libraries; your coding agent (or you) writes the Rust. It can only catch what the
recording covers: see [What it can't catch](#what-it-cant-catch). Only need the slow part fast?
Port just that, one hot path at a time:

| Real workload, same results as the original | Original | With rust-anything |
| --- | ---: | ---: |
| x18n's sidebar search, 50,000 keys (TypeScript, Node) | 10 ms per query | **0.5 ms: 20x faster** |
| The same search in the browser (wasm, one thread) | 10 ms | **0.95 ms: 11.5x** |
| `slugify` over 20,000 strings (Python) | 98 ms | **17x faster** |
| `Shellwords.shellescape` from Ruby's standard library, 50,000 values | 88 ms | **11.8x faster** |
| `Slugify` over 50,000 strings (Go) | 49 ms | **4x faster** |
| `slugify` over 50,000 strings (Java) | 43 ms | **3x faster** |

<p align="center">
  <img src="docs/assets/race.gif" alt="Typing user.profile into x18n's search over 50,000 keys: TypeScript spends 143 ms, the rust-anything batch 6.9 ms, with the same results at every keystroke." width="820">
</p>

Measured on 4 cores; every number has a benchmark in [`demo/`](./demo) that first checks the
results are identical. Calling Rust once per small function is usually *slower* than a JIT;
rust-anything finds the loop worth moving, and moves it.

> rust-anything is an independent project, not affiliated with or endorsed by the Rust Project
> or the Rust Foundation. "Rust" is a trademark of the Rust Foundation.

## Quick start

Paste this into Claude Code, Codex, Cursor or Gemini CLI and let your agent install it:

```text
Install rust-anything: run `cargo install rust-anything`, then `rust-anything setup`.
Tell me when to restart you.
```

Or yourself:

```sh
cargo install rust-anything   # from crates.io
rust-anything setup           # registers it with Claude Code, Codex, Cursor and Gemini CLI
```

No Rust toolchain yet? Prebuilt binaries for macOS, Linux and Windows are attached to each
[GitHub release](https://github.com/erkamyaman/rust-anything/releases), and for JavaScript
projects `npm install -g rust-anything` installs the same binary.

In Claude Code you can also install it as a plugin (the MCP server and the skill; the CLI above
must be on your `PATH`):

```text
/plugin install rust-anything --marketplace erkamyaman/rust-anything
```

`setup` adds the MCP server to each agent it finds and installs the workflow skill where the agent
reads skills. It keeps your other settings, is safe to run again, and `--remove` undoes it.
Then ask your agent, for example:

- *"Rewrite this CLI in Rust with rust-anything, end to end, and prove it behaves the same."*
- *"This search feels slow. Profile it with rust-anything and move the hot loop to Rust."*
- *"Plan a migration of `src/parser/` to Rust with rust-anything; port the first unit and prove it."*
- *"Bench the Rust port in `rust/text-rs` against the original and tell me whether to ship it."*

### Works with

| Agent | `rust-anything setup` adds |
| --- | --- |
| Claude Code | MCP server in `~/.claude.json`, skill in `~/.claude/skills/` |
| Codex | MCP server in `~/.codex/config.toml`, skill in `~/.codex/skills/` |
| Cursor | MCP server in `~/.cursor/mcp.json` |
| Gemini CLI | MCP server in `~/.gemini/settings.json` |
| Any other MCP client | add `rust-anything mcp` as a stdio server by hand (see [Install](#install)) |

Before changing a file that exists, `setup` saves a copy beside it (`<file>.rust-anything.bak`).

Or run the steps yourself:

<p align="center">
  <img src="docs/assets/terminal.gif" alt="rust-anything profile finds fuzzyScore in a loop, bridge --batch generates the Rust crate, gate passes with 2000/2000 recorded cases, and the benchmark shows 20.7x faster than TS." width="820">
</p>


```sh
rust-anything profile . -- node bench.mjs              # what is hot, and who calls it
rust-anything bridge . src/fuzzy.ts --batch fuzzyScore:text
# write src/port.rs (or let your agent), then:
rust-anything record rust/fuzzy-rs && rust-anything build rust/fuzzy-rs
rust-anything diff rust/fuzzy-rs                       # every recorded case must match
rust-anything bench rust/fuzzy-rs                      # faster? the verdict says
rust-anything gate rust/fuzzy-rs                       # done means this passes
```

rust-anything does not translate code: your coding agent (Claude Code, Codex, Cursor, ...) or you write
the Rust. rust-anything supplies what an agent cannot guess reliably: where the time goes, what to port
first and in which order, a bridge so the rest of the code calls the Rust with its API unchanged,
the exact behavior the port must match, a safe way to ship it, and a gate that says when a port is
done.

## Languages

| Language | Unit | Bridge | Recorded and replayed by |
| --- | --- | --- | --- |
| TypeScript/JavaScript | folder or file | napi-rs or wasm-bindgen with a generated binary wire; classes and async included | Node, running the `.ts` sources |
| Python | package or module | PyO3 (abi3), direct conversion, typed exceptions | Python, importing the original |
| C | `.c` file | `extern "C"` functions with the original names and a header | the original compiled to a shared library, called through ctypes, one fork per case |
| Go | package | typed cgo calls and a generated binary wire, in a package with the original API | a generated Go driver, built as its own module |
| Ruby | file or folder of module functions | a magnus extension under the original modules | a generated Ruby driver |
| Java | package of `public static` methods | typed JNI and a generated binary wire, in wrapper classes with the original methods | a generated reflection driver |
| PHP (preview) | folder of functions and `public static` methods | coming next: PHP FFI over a C ABI | whole apps today: `app record`, `app replay` and the front door, for CLIs and servers (`php -S`) |

Every language except C also gets batch classes (`--batch`): the items cross once and stay in
Rust, and each call runs over all of them on all cores.

The language is detected from the repository (`go.mod`, `pom.xml`, `pyproject.toml`, `Gemfile`,
`composer.json`, `package.json`, else the most common source files); `--lang` overrides it. Types
come from the source: TS types, Python hints, C and Go and Java signatures, Ruby YARD tags, PHP
types and phpdoc; untyped parameters used as numbers are inferred as numbers.

PHP is in preview: `analyze` plans a PHP app (Composer packages and PSR-4 autoloading, risks
such as loose comparison and integer overflow into floats, Composer packages mapped to crates),
and a PHP CLI or server can be recorded, replayed and put behind a Rust front door. Porting its
units into Rust through PHP's FFI is the next step ([issue #2](https://github.com/erkamyaman/rust-anything/issues/2)).

## How it works

```
profile ──> analyze ──> bridge ──> record ──> port.rs ──> diff ──> bench ──> shadow ──> gate
 where the    what to     the Rust   what the    you or      every     faster?    both side   done means
 time goes    port first  crate and  original    your agent  recorded  the        by side in  this passes
                          wrapper    does        write it    case      verdict    production
```

The original stays the source of truth: `record` runs it on edge cases (and your own inputs) and
saves what it returns or throws; `diff` replays every case against the Rust; nothing ships until
they all match and `gate` passes. Callers keep the original API throughout.

A whole app goes through the same loop unit by unit, inside a frame that proves the whole
program ([Port a whole app](#port-a-whole-app)):

```
analyze --whole-app ──> app record ──> app front-door ──> per unit: the loop above, then app wire ──> app lift
 shape, every           what the app    Rust owns the       gate passes, so the unit answers in         pure Rust,
 dependency, the        does from the   entry point; the     Rust: replay 100%, fallback rate down      proved by
 decisions to make      outside         original answers                                                replay
```

## The loop

| Step | Command | What it does |
| --- | --- | --- |
| 0. Profile | `rust-anything profile <repo> -- node bench.mjs` | Runs a real workload under the language's profiler (node, cProfile, `go test` pprof, JFR, a Ruby tracer): hot functions by inclusive time, their callers, and which loops to batch; flags code that is already compiled (numba, Cython, JAX), where Rust gains little |
| 1. Plan | `rust-anything analyze <repo>` | Units, port order, risks with `file:line`, bridge per unit, dependency-to-crate fit, best first ports; `--whole-app` adds entry points and shape, every dependency (imported or declared) with its crate, pieces (units that import each other move together) and numbered decisions with a recommended answer |
| 2. Bridge | `rust-anything bridge <repo> <unit>` | Crate with the bindings (`lib.rs`, plus the wrapper the source language loads) and stubs to port (`port.rs`); `--batch fn:param` adds a class that keeps many `param` values in Rust |
| 3. Record | `rust-anything record <crate>` | Runs the original on generated edge cases (non-ASCII, emoji, `-0`, `NaN`, ints where floats are expected, ...) and on every semantic trap in every parameter (string length and case, signed division, overflow edges, float printing, map and sort order), and saves `cases.jsonl`; `--float-tolerance 1e-9` lets floats match within that share for numeric code |
| 3. Build | `rust-anything build <crate>` | Builds the Rust side: `.node`, wasm package, Python extension or shared library |
| 3. Diff | `rust-anything diff <crate>` | Replays the recorded cases against Rust, called the way the original's callers call it; lists mismatches |
| 3. Bench | `rust-anything bench <crate>` | Times the recorded cases on the original and on Rust, bridge included |
| 4. Shadow | `rust-anything shadow <crate>` | Drop-in that runs both, returns the original's result, reports mismatches; `RUST_ANYTHING_MODE=old\|shadow\|new` |
| 5. Gate | `rust-anything gate <crate>` | fmt, clippy `-D warnings`, tests, `unsafe` audit, nothing unported, a recorded failing case for every error path of the original, no `unwrap`/`expect`/`panic!` where the original returns an error (unless marked `// INFALLIBLE: <why>`), build, API, behavior |
| Agents | `rust-anything setup` | Registers the MCP server (`rust-anything mcp`, every step as a tool) and the workflow skill ([`skills/rust-anything/SKILL.md`](./skills/rust-anything/SKILL.md)) with your coding agents |

## Port a whole app

The goal is a pure Rust app that behaves like the original, with the original kept as reference.
Your agent writes the Rust; rust-anything orders the work, scaffolds it, and proves every step.
The [whole-app skill](./skills/rust-anything/whole-app.md) walks the agent through it, starting
with the decisions only you can make:

- **Grilling**: the agent asks in rounds, each question with its recommended answer, until every
  decision the port depends on is settled, and writes each one as an ADR in `rust/DECISIONS.md`,
  with `rust/GLOSSARY.md` mapping the original's terms to Rust names.
- **Research**: background agents read each dependency's primary sources and write
  `rust/research/<topic>.md`, with every semantic trap they found.
- **Across sessions**: `rust/MAP.md` lists every unit with its state; a session claims one unit
  before it starts, and each checkpoint leaves a `rust/HANDOFF.md` for the next session. Units in
  one wave can be ported in parallel by subagents.
- **Cutover**: the agent does what it can and writes `rust/cutover.sh`, an interactive script for
  the steps only you can do (deploys, DNS, secrets), with a way back at each step.

Grilling, research and these practices are adapted from
[Matt Pocock's skills](https://github.com/mattpocock/skills).

Plan first: `rust-anything analyze . --whole-app` adds the app's shape (CLI, server or library)
and entry points, every external dependency (imported or declared) with its Rust crate and fit,
the port order as pieces (units that import each other move together), and numbered decisions
with a recommended answer: keep units, blocked units, dependencies with no or a partial crate.

Then prove the whole program from the outside. `record` and `diff` prove one unit; `app record`
and `app replay` prove the app, for CLIs and servers in any of the six languages (the app is a
black box):

```sh
rust-anything app record . -- python3 cli.py          # the command that runs the original
rust-anything app replay .                            # the original must pass 100%
rust-anything app replay . --build "target/release/mytool"
```

- `app record` runs the original on the app's own documented examples (`$ mytool ...` lines in
  its Markdown and shell files, with the files they name), an `--inputs` JSONL file
  (`{"name", "args", "stdin", "env", "files"}`), and semantic traps derived from those cases
  (non-ASCII and emoji strings, negative division and modulo, overflow, large and tiny floats,
  map order, missing files). Each case runs twice; what differs between the two runs becomes a
  `[..]` wildcard. `--normalize timestamps|uuids|key-order` or `--normalize name=regex` adds
  normalizers, saved with the cases.
- Cases are [trycmd](https://docs.rs/trycmd) files in `rust/app-cases/`: `<case>.toml` (argv, env,
  exit code), `.stdin`, `.stdout`, `.stderr`, `.in/` (files in) and `.out/` (files written). Read
  and edit them by hand; a Rust test can run them with `trycmd` once the port has a binary.
- `app replay` runs any build against the cases, prints `passed/total`, writes
  `rust/app-cases/replay-report.md` with a diff per failing case, and exits non-zero on any
  mismatch. A build that appends to the file named by `RUST_ANYTHING_FALLBACK_LOG` (one line per
  fallback to the original), as the front door below does, also gets its fallback rate reported.
- `app replay --case <name>` reruns one case by the name the report gives it: the fast,
  repeatable loop for fixing a mismatch before running everything again.

Then move the entry point to Rust and hand it commands one unit at a time:

```sh
rust-anything app front-door .                            # rust/app: every command runs the original
rust-anything app wire . textkit --command upper          # after textkit-rs passes gate
# write the glue in rust/app/src/units/textkit.rs, then:
rust-anything app wire . textkit                          # 100% again, lower fallback rate
```

- `app front-door` scaffolds `rust/app`, a Rust binary named after the app: a clap parser for the
  commands and flags in the recorded cases, where every command runs the original with the same
  argv, stdin and environment and passes its output and exit code through. Each fallback is
  counted, so replaying the fresh front door gives 100% passed at 100% fallback (it builds and
  replays to show it). It never overwrites `rust/app`: the code is yours from then on.
- `app wire <repo> <unit> --command <name>` runs `gate` on the unit crate (`--skip-gate` if it just
  passed), adds it to `rust/app` as a library, writes `src/units/<unit>.rs` once for you or your
  agent to fill in (parse the arguments, call `<crate>::port`, print what the original prints),
  routes the commands to it, then builds and replays. `RUST_ANYTHING_UNIT_<NAME>=original` sends a
  wired unit back to the original until the lift.

Wire the app's own name as a command (`--command mytool`) for argv that names no command: no
arguments, unknown commands, usage errors.

When replay passes with fallback rate 0 and every unit passes gate, make it a pure Rust app:

```sh
rust-anything app lift .
```

- `app lift` refuses until both hold, and says what blocks it: the cases still falling back,
  glue still a stub, units failing gate.
- On a copy first, it removes the fallback path and the kill switches, turns each unit crate into
  a plain library of `rust/app` (no `cdylib`, bindings or generated wrappers), and adds
  `rust/app/tests/app_cases.rs`, which runs `rust/app-cases` with trycmd on `cargo test`, so CI
  needs nothing but cargo.
- Then it runs the lift checklist: fmt, clippy `-D warnings` and tests on every unit and on
  `rust/app`, every target named in `rust/DECISIONS.md` built or checked where it is installed,
  files read at run time and asset folders not embedded, and replay on the pure binary. Only when
  all of it passes are the changes written back. The original is never touched.

### Servers

The same commands prove HTTP servers. `--http` says the command starts a server; it takes its
port from `PORT` or `{port}` in the command (`--port` for one that always listens on the same
port):

```sh
rust-anything app record . --http -- node server.js
rust-anything app replay .
rust-anything app front-door .                                    # axum: every route proxied
rust-anything app wire . api --route 'GET /users/{id}' --route '*'
rust-anything app lift .
```

- Requests come from `curl` lines in the app's docs (`curl -X POST -d ... http://localhost:8080/x`),
  `--inputs` (`{"name", "method", "path", "headers", "body"}`) and traps: path segments and query
  values swapped for the same traps as CLI arguments, bodies for text and JSON traps, and an
  unknown route. Each run starts the server fresh and sends the requests in name order, so state
  between requests is kept.
- Cases are `rust/app-cases/http/<case>.toml` (the request, the status and the headers that matter)
  and `<case>.body` (the response body, with `[..]` where two runs differed). Date, server and
  other per-response headers are left out; delete any header line you do not care about.
- The front door is an axum server that starts the original on a port of its own and proxies
  every route no unit answers. `wire --route` takes axum routes: `METHOD /path/{param}`, `/path`
  for any method, `*` for everything else; the glue gets the route, its parameters and the
  request. `lift` removes the proxy; HTTP cases then run in CI with `app replay`.

### Libraries

A library has no process to replay: its public API is the front door, and each unit's recorded
cases are the proof.

```sh
rust-anything app front-door .        # rust/app: a Rust crate with the public API
# each unit through the loop: bridge, record, port.rs, build, diff, gate; then:
rust-anything app wire . textkit-rs   # re-exported from rust/app; the original imports its shadow
rust-anything app replay .            # every wired unit's cases; fallback = exports still in the original
rust-anything app lift .
```

- `app front-door` finds the public API (every unit's exports) when the repository has no `main`
  and no server (`--library` otherwise), and scaffolds `rust/app` as a library crate. Each wired
  unit becomes a module of it: `pub use textkit_rs::port as textkit;`.
- `app wire` takes a crate made by `bridge`, runs `gate`, and writes the unit's shadow drop-in:
  the original package imports it in place of the unit, so its callers keep the original API and
  reach the Rust. `RUST_ANYTHING_UNIT_<NAME>=original` sends the unit back (C: build without the
  shadow's flags).
- `app replay` runs every wired unit's recorded cases through its bindings. The fallback rate is
  the share of public exports Rust does not answer yet: unwired units, and exports `bridge` keeps
  in the original language.
- `app lift` needs fallback 0 and every unit through `gate`; it strips the bindings, wrappers and
  shadows from the units and leaves `rust/app` as one pure Rust library. It does not touch any
  `port.rs`, so the cases that matched through the bindings still describe it; the checklist
  warns about files of the original that still import the shadows.

All five are MCP tools too: `app_record`, `app_replay`, `app_front_door`, `app_wire` and
`app_lift`.

## Case study: x18n's core

All 29 functions of x18n's core that can move without an API change were ported with rust-anything:
every gate passes and 7,925 recorded cases match exactly. `rust-anything bench` then showed the ports
are slower than the TS as called from JS, because the bridge costs more than the work. Full report:
[`demo/x18n-core`](./demo/x18n-core/README.md). The lesson is built in: measure with `bench` before
shipping a port.

## Hot paths: keep the data in Rust

A port called once per item pays the bridge once per item, and loses to a JIT. What wins is
moving the loop: `profile` finds it, and `--batch` generates a class that takes the items once
and runs the function over all of them per call, on all cores, with typed-array results.

```sh
rust-anything profile ../x18n -- node --experimental-strip-types $PWD/demo/x18n-search/search.ts .
# -> fuzzyScore: a quarter of the run, called per key by `matched`: batch it
rust-anything bridge ../x18n packages/core/src/fuzzy.ts --batch fuzzyScore:text
```

```js
const search = new FuzzyScoreBatch(keys)          // once
const order = search.rank(query, 0)               // per keystroke: indexes, best first
```

A `FuzzyScoreIndex` struct in `port.rs` replaces the default loop with one that prepares the
items once, and can rank by itself (`rank`): it keeps the keys lowercased with a character mask
each, a table of each key's first position of every common character (a one-letter query is one
column), and the last query's matches (typing `se` after `s` rescores only what `s` matched). On
x18n's sidebar search over 50,000 keys, typed letter by letter, with identical results:

| | Per query | vs TS |
| --- | ---: | ---: |
| TS: `map(fuzzyScore)`, filter, sort | 10 ms | 1x |
| TS with the same narrowing as the index | 4.1-5.4 ms | 2x |
| The same port, called per key | - | 0.2-0.4x |
| `FuzzyScoreBatch`, default index (4 cores) | 5.1 ms | 1.7x |
| `FuzzyScoreBatch` with `FuzzyScoreIndex` (napi, 4 cores) | 0.45-0.56 ms | **18-22x** |
| The same with wasm (one thread) | 0.95 ms | **11.5x** |

Against TS doing the same narrowing, Rust is still 7-12x faster (wasm 5x). Turn the returned
indexes into keys with a plain loop: `Array.from(order, i => keys[i])` cost 20x more, 0.4 ms.

Every language gets batches, and they beat the original even where per-call ports lose. The
same work on 4 cores, identical results and errors (benchmarks in each demo folder):

| Language | Workload | Original | Per-call port vs original | Batch vs original |
| --- | --- | ---: | ---: | ---: |
| TS | x18n search, 50,000 keys | 10 ms | 0.2-0.4x | **20x** |
| Python | `slugify`, 20,000 strings | 98 ms | - | **17x** |
| Ruby | `slugify`, 20,000 strings | 110 ms | - | **12.7x** |
| Ruby | `shellescape` (stdlib), 50,000 mixed values | 88 ms | - | **11.8x** |
| Go | `Slugify`, 50,000 strings | 49 ms | 0.93x | **4x** |
| Java | `slugify`, 50,000 strings | 43 ms | 0.68x | **3x** |

Compiled originals gain less: the per-item work is already fast, so the batch wins by the number of
cores. Batch crates allocate with mimalloc: with the system allocator the Go batch was slower than
one thread. Demo: [`demo/x18n-search`](./demo/x18n-search/README.md).

## Real code in six languages

Go's `path`, Ruby's `shellwords`, Python's `colorsys`, JDK and glibc behavior behind small
facades: every port passes its gate, 13,010 recorded cases in all. The runs found and fixed
bugs in rust-anything (floats off by one ULP through `serde_json`, C crashes during recording,
untyped code getting garbage inputs). Called per function, the Ruby port runs 4.4x faster than
Ruby and the Python port 1.35x faster than CPython, while Go and Java leaf functions stay faster
in their own language; as batches, all of them win (see the table above).
Report: [`docs/real-world-languages.md`](./docs/real-world-languages.md).

## Example: a real module from x18n

`packages/core/src/fuzzy.ts` from [x18n](https://github.com/x18n-dev/x18n), ported both ways in
[`demo/`](./demo):

```sh
rust-anything analyze ../x18n                                      # fuzzy.ts: ready, wasm-bindgen (core runs in browsers)
rust-anything bridge ../x18n packages/core/src/fuzzy.ts --out demo/fuzzy-rs
rust-anything record demo/fuzzy-rs --count 2000
# write src/port.rs
rust-anything gate demo/fuzzy-rs
```

A first port that indexed by Rust `char` passed simple tests but failed `diff`:

```
198/200 cases match
- fuzzyScore("b😀", "a😀b😀c"): expected {"ok":1997}, got {"ok":1998}
```

JS `indexOf` counts UTF-16 code units, so an emoji is two positions. The port in
`demo/*/src/port.rs` uses the generated `utf16` helpers and passes 2000/2000 cases and the gate,
as napi-rs (`demo/fuzzy-napi`) and as wasm-bindgen (`demo/fuzzy-rs`).

The plan rust-anything writes for all of x18n: [`docs/examples/x18n.md`](./docs/examples/x18n.md).

## Install

```sh
cargo install --path .
```

`record`, `diff` and `bench` run the original in its own runtime: Node 22.6+ for TS (it runs `.ts`
sources directly), Python 3.9+ for Python and C (ctypes), Go 1.21+, Ruby 3+, JDK 17+
(`javac` and `java`). C also needs a C compiler. wasm bridges also need `rustup target add wasm32-unknown-unknown` and
`cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked`; `build` names
the exact version.

For agents, `rust-anything setup` registers everything (see Quick start). To add the MCP server to
one project by hand instead (`.mcp.json`):

```json
{ "mcpServers": { "rust-anything": { "command": "rust-anything", "args": ["mcp"] } } }
```

## What `bridge` decides

- Exports that cannot cross a bridge stay in the source language, with the reason, and the shadow
  module re-exports the original. For TS:
  functions that take or return functions, generators and iterators, RegExp, `instanceof` checks,
  generics, and values whose types (followed through imports, re-exports and `extends`) hold
  functions. `--keep "name: reason"` keeps more, e.g. code that depends on `Intl` data.
- TS types map to Rust types, with type aliases resolved through imports and parameter types
  inferred from default values; structured values cross as a generated binary wire (JSON only
  as a fallback for shapes the wire does not model).
- JSON cannot express `undefined`, NaN, Infinity, -0 or lone surrogates: structured values carry
  markers (`{"$undefined": true}`, `{"$num": "NaN"}`, `{"$utf16": [...]}`) that the generated
  `index.cjs` translates, with helpers in the crate's `js.rs`.

`record` runs TS sources as they are: a Node resolve hook follows bundler-style imports
(`./errors` to `./errors.ts`), `--resolve-from` supplies npm packages when the repo has none
installed, and TS that needs transforming (enums, parameter properties) is retried with
`--experimental-transform-types`.

## What `analyze` looks at

- Packages (`package.json`) and source files; skips `node_modules`, build output, fixtures,
  playgrounds, tool configs. Vue/Svelte/Astro `<script>` blocks are parsed for imports.
- **Units**: a folder of source files, or a file at a package's source root.
- **Waves**: a unit's imports come in earlier waves; import cycles are ported together.
- **Bridge**: napi-rs when the unit or anything it imports needs Node; wasm-bindgen for portable
  code; keep in JS for UI and editor code.
- **Readiness** (how safe) and **priority** (safe and worth it: loops and string work, tests, size).

| Risk | Severity | Example |
| --- | --- | --- |
| String offsets | high | `slice`, `indexOf`, `matchAll`, the `d` flag: UTF-16 vs UTF-8 |
| Regex syntax | high | lookaround, backreferences, `y`: not in the `regex` crate |
| Dynamic regex | high | `new RegExp(userPattern)`: JS syntax at runtime |
| Dynamic code | high | `eval`, `new Function`, computed `import()` |
| Dynamic typing | medium | `any`, `'key' in value` |
| Ordered collections | medium | `Map`, `Set`, `Object.keys`: insertion order |
| Async, generators | medium | promise and generator boundaries |
| Class inheritance, reflection | medium | `extends`, `Proxy`, `Reflect`, `Symbol` |
| Callback-shaped APIs | medium | function-typed params and methods: chatty bridges |
| Exceptions, numbers, JSON | low | `throw`, bitwise ops, `JSON.stringify` order |

## Development

```sh
cargo test                        # unit tests, fixture r...

© Erkam Yaman · MIT · erkamyaman/rust-anything

Похожие плагины

Все плагины по теме «Языки программирования» →
rust-best-practices apollographql Скилл rust-best-practices для написания и ревью Rust-кода по хендбуку Apollo GraphQL: заимствование против клонирования, обработка ошибок, тесты. CX Codex +1 23 400установок rust-async-patterns Seth Hobson Скилл rust-async-patterns для Claude Code помогает писать и разбирать асинхронный Rust на Tokio: задачи, каналы, потоки и обработку ошибок. Помогает создавать сетевые сервисы и отлаживать код. CX Codex +1 20 625установок rust-mcp-server-generator официальный github Скилл rust-mcp-server-generator для GitHub Copilot создаёт проект MCP-сервера на Rust с помощью SDK rmcp. Он подключается к задаче, когда нужно задать серверу инструменты, транспорт и другие компоненты. CX Codex +1 9 181установок rust-testing affaan-m Скилл rust-testing для Claude Code и других платформ: юнит-тесты, интеграционные, async, property-based, моки и покрытие в Rust. Держит единый стиль тестов по циклу TDD. CX Codex +1 8 400установок rust-skills leonardomso 265 правил написания идиоматичного Rust по 26 категориям. Загружается командой /rust-skills перед генерацией или ревью кода. CX Codex +1 7 400установок rust-patterns affaan-m Скилл rust-patterns задаёт правила идиоматичного Rust: управление владением, типизированные ошибки, сопоставление с образцом и трейты. Пригодится при написании, рефакторинге и ревью Rust-кода. CX Codex +1 7 000установок

Из того же набора2

Спонсоры проекта

Компании, которые помогают держать аналитику открытой