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.6.0: C# / .NET

EL4CTEOf927b3a9d7b2
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index cd83dd2..23b8063 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "fast-anything",
- "version": "0.5.1",
+ "version": "0.6.0",
"description": "Find the slow 5% of your app, port just that to Rust, and prove it still behaves the same.",
"author": {
"name": "EL4CTEO"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 98b6b14..dcdc262 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -42,6 +42,9 @@ jobs:
with:
go-version: stable
cache: false
+ - uses: actions/setup-dotnet@v6
+ with:
+ dotnet-version: "10.0.x"
- uses: gradle/actions/setup-gradle@v6
- uses: Swatinem/rust-cache@v2
- run: cargo fmt --check
@@ -157,6 +160,20 @@ jobs:
$fa bench --runs 2
$fa disable
git diff --exit-code src
+ - name: end to end, C#
+ working-directory: examples/fuzzy-dedupe-cs
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- dotnet run -c Release
+ $fa port
+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs
+ $fa verify
+ $fa enable
+ dotnet run -c Release
+ $fa bench --runs 2
+ $fa disable
+ git diff --exit-code Fuzzy.cs
+ test -z "$(git status --porcelain .)"
- name: end to end, C
working-directory: examples/mandelbrot-c
run: |
diff --git a/.gitignore b/.gitignore
index e46214b..776818e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,7 @@
**/.fast/target/
**/.fast/lib/
examples/*/.fast/
+examples/*/bin/
+examples/*/obj/
+src/csharp/bin/
+src/csharp/obj/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 845b1fd..1371feb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## 0.6.0
+
+- C# / .NET 8+: `fast-anything scan -- dotnet run -c Release`. Profiled with the runtime's own EventPipe sampler (nothing to install), sources read with Roslyn, ports called through NativeLibrary. Static methods taking numbers, strings, arrays, lists and string-keyed dictionaries; verify adds edge cases and shrunk inputs. Thanks @JuggyBob for the request (#3).
+
## 0.5.1
- Python: keyword arguments get edge cases and smaller inputs in verify; `bytes`, `bytearray` and `tuple[T, ...]` map to Rust types; fixed generated byte literals. Thanks @ashp15205 (#1).
diff --git a/Cargo.lock b/Cargo.lock
index 013f4dd..fdc1c94 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -112,7 +112,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "fast-anything"
-version = "0.5.1"
+version = "0.6.0"
dependencies = [
"anyhow",
"clap",
diff --git a/Cargo.toml b/Cargo.toml
index 6db17fb..9180354 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "fast-anything"
-version = "0.5.1"
+version = "0.6.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."
@@ -9,7 +9,7 @@ readme = "README.md"
repository = "https://github.com/EL4CTEO/fast-anything"
keywords = ["performance", "python", "nodejs", "java", "ai-agents"]
categories = ["command-line-utilities", "development-tools::profiling"]
-exclude = ["examples/*/.fast", ".github", "docs/assets"]
+exclude = ["examples/*/.fast", "examples/*/bin", "examples/*/obj", ".github", "docs/assets"]
[[bin]]
name = "fast-anything"
diff --git a/README.md b/README.md
index 20b6da9..1ab0796 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@
<a href="https://www.npmjs.com/package/@el4cteo/fast-anything"><img src="https://img.shields.io/npm/v/@el4cteo/fast-anything?color=f74c00&label=npm" alt="npm"></a>
<a href="https://crates.io/crates/fast-anything"><img src="https://img.shields.io/crates/v/fast-anything?color=f74c00" alt="crates.io"></a>
<a href="https://github.com/EL4CTEO/fast-anything/actions/workflows/ci.yml"><img src="https://github.com/EL4CTEO/fast-anything/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
- <img src="https://img.shields.io/badge/Python%20%C2%B7%20Node%20%C2%B7%20TypeScript%20%C2%B7%20Ruby%20%C2%B7%20Java%20%C2%B7%20Go%20%C2%B7%20PHP%20%C2%B7%20C%20%C2%B7%20C%2B%2B-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Go, PHP, C, C++">
+ <img src="https://img.shields.io/badge/Python%20%C2%B7%20Node%20%C2%B7%20TypeScript%20%C2%B7%20Ruby%20%C2%B7%20Java%20%C2%B7%20Go%20%C2%B7%20PHP%20%C2%B7%20C%20%C2%B7%20C%2B%2B%20%C2%B7%20C%23-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Go, PHP, C, C++, C#">
<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>
@@ -65,6 +65,7 @@ Real runs on an i5-10500, Windows 11 (C and C++: a 4-core GitHub Actions Linux r
| PHP fuzzy dedupe (600 names) | 2.94s | **53ms, 55×** |
| Go fuzzy dedupe (3,000 names) | 3.02s | **144ms, 21×** |
| Ruby fuzzy dedupe (400 names) | 3.13s | **228ms, 14×** |
+| C# fuzzy dedupe (4,000 names) | 4.03s | **312ms, 13×** |
| Java fuzzy dedupe (4,000 names) | 3.50s | **1.18s, 3×** (11× on the function; the rest is JVM startup) |
| C mandelbrot (8 zoom levels) | 431ms | **127ms, 3.4×** |
| C++ fuzzy dedupe (6,000 names) | 3.02s | **1.09s, 2.7×** |
@@ -94,10 +95,11 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo) | ✅ |
| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ |
| C and C++ (gcc or clang: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |
+| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |
-It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Java and PHP that means static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
+It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Java, C# and PHP that means static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
-Ruby, Java, Go, PHP, C and C++ need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.
+Ruby, Java, Go, PHP, C, C++ and C# need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.
## License
diff --git a/examples/fuzzy-dedupe-cs/Fuzzy.cs b/examples/fuzzy-dedupe-cs/Fuzzy.cs
new file mode 100644
index 0000000..0eeff38
--- /dev/null
+++ b/examples/fuzzy-dedupe-cs/Fuzzy.cs
@@ -0,0 +1,42 @@
+// Fuzzy string matching helpers.
+static class Fuzzy
+{
+ // Edit distance: how many inserts, deletes or substitutions turn a into b.
+ static int Levenshtein(string a, string b)
+ {
+ if (a.Length < b.Length) (a, b) = (b, a);
+ var previous = new int[b.Length + 1];
+ for (int j = 0; j <= b.Length; j++) previous[j] = j;
+ for (int i = 1; i <= a.Length; i++)
+ {
+ var current = new int[b.Length + 1];
+ current[0] = i;
+ for (int j = 1; j <= b.Length; j++)
+ {
+ int cost = a[i - 1] == b[j - 1] ? 0 : 1;
+ current[j] = Math.Min(Math.Min(previous[j] + 1, current[j - 1] + 1), previous[j - 1] + cost);
+ }
+ previous = current;
+ }
+ return previous[b.Length];
+ }
+
+ static string Normalize(string name) =>
+ string.Join(" ", name.ToLowerInvariant().Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));
+
+ // Index pairs of names within maxDistance edits of each other.
+ public static int[][] FindDuplicates(string[] names, int maxDistance)
+ {
+ var clean = new string[names.Length];
+ for (int i = 0; i < names.Length; i++) clean[i] = Normalize(names[i]);
+ var pairs = new List<int[]>();
+ for (int i = 0; i < clean.Length; i++)
+ {
+ for (int j = i + 1; j < clean.Length; j++)
+ {
+ if (Levenshtein(clean[i], clean[j]) <= maxDistance) pairs.Add([i, j]);
+ }
+ }
+ return pairs.ToArray();
+ }
+}
diff --git a/examples/fuzzy-dedupe-cs/FuzzyDedupe.csproj b/examples/fuzzy-dedupe-cs/FuzzyDedupe.csproj
new file mode 100644
index 0000000..0ece068
--- /dev/null
+++ b/examples/fuzzy-dedupe-cs/FuzzyDedupe.csproj
@@ -0,0 +1,10 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ </PropertyGroup>
+
+</Project>
diff --git a/examples/fuzzy-dedupe-cs/Program.cs b/examples/fuzzy-dedupe-cs/Program.cs
new file mode 100644
index 0000000..813f61c
--- /dev/null
+++ b/examples/fuzzy-dedupe-cs/Program.cs
@@ -0,0 +1,33 @@
+// Find near-duplicate customer names, the slow way.
+// dotnet run -c Release
+
+string[] first = ["Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",
+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"];
+string[] last = ["Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka",
+ "Wang", "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"];
+
+var rng = new Random(7);
+var names = new string[4000];
+for (int k = 0; k < names.Length; k++)
+{
+ string name = first[rng.Next(first.Length)] + " " + last[rng.Next(last.Length)];
+ if (rng.NextDouble() < 0.35)
+ {
+ int i = rng.Next(name.Length);
+ name = name[..i] + "aeiourstln"[rng.Next(10)] + name[(i + 1)..];
+ }
+ names[k] = name;
+}
+
+int[][] pairs = Fuzzy.FindDuplicates(names, 2);
+Console.WriteLine($"{names.Length} names, {pairs.Length} likely duplicate pairs");
+int shown = 0;
+foreach (var p in pairs)
+{
+ if (shown == 5) break;
+ if (names[p[0]] != names[p[1]])
+ {
+ Console.WriteLine($" {names[p[0]]} ~ {names[p[1]]}");
+ shown++;
+ }
+}
diff --git a/examples/fuzzy-dedupe-cs/reference/port.rs b/examples/fuzzy-dedupe-cs/reference/port.rs
new file mode 100644
index 0000000..dd882ce
--- /dev/null
+++ b/examples/fuzzy-dedupe-cs/reference/port.rs
@@ -0,0 +1,75 @@
+//! Reference port of Fuzzy.FindDuplicates (with Levenshtein and Normalize inside it):
+//! what a good agent run produces. CI uses it to test the pipeline without an agent.
+#![allow(non_snake_case)]
+
+/// C#'s string.Join(" ", s.ToLowerInvariant().Trim().Split((char[]?)null, RemoveEmptyEntries)), as UTF-16 units.
+/// ToLowerInvariant is the simple, one-to-one case mapping: no final sigma, and İ becomes a plain i.
+fn normalize(name: &str) -> Vec<u16> {
+ let lower: String = name.chars().map(|c| if c == 'İ' { 'i' } else { c.to_lowercase().next().unwrap_or(c) }).collect();
+ let mut out = Vec::with_capacity(lower.len());
+ for word in lower.split_whitespace() {
+ if !out.is_empty() {
+ out.push(u16::from(b' '));
+ }
+ out.extend(word.encode_utf16());
+ }
+ out
+}
+
+pub fn FindDuplicates(names: Vec<String>, maxDistance: i32) -> Result<Vec<[i32; 2]>, String> {
+ if maxDistance < 0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<u16>> = names.iter().map(|n| normalize(n)).collect();
+ Ok(pairs(&clean, maxDistance as usize).into_iter().map(|(i, j)| [i as i32, j as i32]).collect())
+}
+
+/// Edit distance, one row on the shorter side, common prefix and suffix skipped.
+fn distance<T: PartialEq>(a: &[T], b: &[T], row: &mut Vec<usize>) -> usize {
+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[prefix..], &b[prefix..]);
+ let suffix = a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[..a.len() - suffix], &b[..b.len() - suffix]);
+ let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
+ if short.is_empty() {
+ return long.len();
+ }
+ row.clear();
+ row.extend(0..=short.len());
+ for (i, ca) in long.iter().enumerate() {
+ let mut diagonal = row[0];
+ row[0] = i + 1;
+ for (j, cb) in short.iter().enumerate() {
+ let above = row[j + 1];
+ row[j + 1] = (above + 1).min(row[j] + 1).min(diagonal + usize::from(ca != cb));
+ diagonal = above;
+ }
+ }
+ row[short.len()]
+}
+
+/// All (i, j) with i < j and distance <= max, in the original loop order, spread over threads.
+fn pairs<T: PartialEq + Sync>(clean: &[Vec<T>], max: usize) -> Vec<(usize, usize)> {
+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(clean.len().max(1));
+ let mut found: Vec<(usize, usize)> = std::thread::scope(|s| {
+ let workers: Vec<_> = (0..threads)
+ .map(|t| {
+ s.spawn(move || {
+ let mut row = Vec::new();
+ let mut out = Vec::new();
+ for i in (t..clean.len()).step_by(threads) {
+ for j in i + 1..clean.len() {
+ if clean[i].len().abs_diff(clean[j].len()) <= max && distance(&clean[i], &clean[j], &mut row) <= max {
+ out.push((i, j));
+ }
+ }
+ }
+ out
+ })
+ })
+ .collect();
+ workers.into_iter().flat_map(|w| w.join().expect("worker panicked")).collect()
+ });
+ found.sort_unstable();
+ found
+}
diff --git a/npm/fast-anything/package.json b/npm/fast-anything/package.json
index a960995..794d019 100644
--- a/npm/fast-anything/package.json
+++ b/npm/fast-anything/package.json
@@ -1,7 +1,7 @@
{
"name": "@el4cteo/fast-anything",
- "version": "0.5.1",
- "description": "Don't rewrite it in Rust. Rewrite the 5% that's slow: profile Python, Node, Ruby, Java, Go, PHP, C or C++ apps, port the hot functions with your coding agent, prove they behave the same.",
+ "version": "0.6.0",
+ "description": "Don't rewrite it in Rust. Rewrite the 5% that's slow: profile Python, Node, Ruby, Java, Go, PHP, C, C++ or C# apps, port the hot functions with your coding agent, prove they behave the same.",
"keywords": [
"rust",
"python",
@@ -13,6 +13,8 @@
"php",
"c",
"cpp",
+ "csharp",
+ "dotnet",
"performance",
"optimization",
"profiler",
@@ -47,11 +49,11 @@
"node": ">=18"
},
"optionalDependencies": {
- "@el4cteo/fast-anything-win32-x64": "0.5.1",
- "@el4cteo/fast-anything-linux-x64": "0.5.1",
- "@el4cteo/fast-anything-linux-arm64": "0.5.1",
- "@el4cteo/fast-anything-darwin-arm64": "0.5.1",
- "@el4cteo/fast-anything-darwin-x64": "0.5.1"
+ "@el4cteo/fast-anything-win32-x64": "0.6.0",
+ "@el4cteo/fast-anything-linux-x64": "0.6.0",
+ "@el4cteo/fast-anything-linux-arm64": "0.6.0",
+ "@el4cteo/fast-anything-darwin-arm64": "0.6.0",
+ "@el4cteo/fast-anything-darwin-x64": "0.6.0"
},
"publishConfig": {
"access": "public"
diff --git a/skills/fast-anything/SKILL.md b/skills/fast-anything/SKILL.md
index e268213..7162f52 100644
--- a/skills/fast-anything/SKILL.md
+++ b/skills/fast-anything/SKILL.md
@@ -1,6 +1,6 @@
---
name: fast-anything
-description: Speed up a slow Python, Node.js/TypeScript, Ruby, Java, Go, PHP, C or C++ app by porting its hottest pure functions to Rust and proving each port gives the same results on real recorded calls. Use when the user wants their Python code faster, asks about hot paths or profiling, or says "rewrite the slow part in Rust".
+description: Speed up a slow Python, Node.js/TypeScript, Ruby, Java, Go, PHP, C, C++ or C# app by porting its hottest pure functions to Rust and proving each port gives the same results on real recorded calls. Use when the user wants their Python code faster, asks about hot paths or profiling, or says "rewrite the slow part in Rust".
---
# fast-anything
@@ -15,7 +15,7 @@ The `fast-anything` CLI measures, records, builds, checks and swaps. You write t
Skip anything under 2% of the run: porting it can't make a visible difference.
2. **Port**: `fast-anything port <id>`. It re-runs the app, records up to 500 real calls, and creates
`.fast/ports/<id>/` with a stub `src/lib.rs` and a `TASK.md`. Read TASK.md fully.
-3. **Write the Rust** in `src/lib.rs` (Ruby, Java, Go, PHP, C, C++: `src/port.rs`; `src/lib.rs` there is generated glue):
+3. **Write the Rust** in `src/lib.rs` (Ruby, Java, Go, PHP, C, C++, C#: `src/port.rs`; `src/lib.rs` there is generated glue):
- Same semantics: Unicode code points (`.chars()`; JavaScript compares UTF-16 units), integer ranges, float operation order, error cases.
- Fast: borrow, no needless allocation, ASCII fast paths, `with_capacity`.
- Keep the function and module names. Run `cargo check` in the crate.
diff --git a/src/backend.rs b/src/backend.rs
index 5b85d00..9ba3f05 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -4,7 +4,7 @@
use crate::hotspot::Hotspot;
use crate::state::{Ctx, Port, Verify};
use crate::util::{output, tail};
-use crate::{cfamily, golang, java, node, php, python, ruby};
+use crate::{cfamily, csharp, golang, java, node, php, python, ruby};
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use std::fs;
@@ -23,6 +23,8 @@ pub enum Lang {
Php,
C,
Cpp,
+ #[serde(rename = "csharp")]
+ CSharp,
}
#[derive(Deserialize)]
@@ -54,18 +56,20 @@ impl Lang {
Ok(Lang::Go)
} else if php::is_php(program) {
Ok(Lang::Php)
+ } else if csharp::is_csharp(program) {
+ Ok(Lang::CSharp)
} else if let Some(lang) = cfamily::detect(program) {
Ok(lang)
} else {
bail!(
- "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java, Go, PHP, C and C++. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run .\n fast-anything scan -- php app.php\n fast-anything scan -- clang -O2 main.c (or gcc, g++, clang++)"
+ "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java, Go, PHP, C, C++ and C#. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run .\n fast-anything scan -- php app.php\n fast-anything scan -- clang -O2 main.c (or gcc, g++, clang++)\n fast-anything scan -- dotnet run -c Release"
)
}
}
/// Ports called through the C entry point, with the port in src/port.rs.
pub fn c_bridge(self) -> bool {
- matches!(self, Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp)
+ matches!(self, Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp)
}
pub fn label(self) -> &'static str {
@@ -78,6 +82,7 @@ impl Lang {
Lang::Php => "PHP",
Lang::C => "C",
Lang::Cpp => "C++",
+ Lang::CSharp => "C#",
}
}
@@ -90,6 +95,7 @@ impl Lang {
Lang::Go => golang::resolve(program, root),
Lang::Php => php::resolve(program, root),
Lang::C | Lang::Cpp => cfamily::resolve(program, root),
+ Lang::CSharp => csharp::resolve(program, root),
}
}
@@ -102,6 +108,7 @@ impl Lang {
Lang::Go => golang::profile(ctx, exe, args),
Lang::Php => php::profile(ctx, exe, args),
Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),
+ Lang::CSharp => csharp::profile(ctx, exe, args),
}
}
@@ -122,6 +129,7 @@ impl Lang {
Lang::Go => golang::record(ctx, exe, args, hs, out, limit),
Lang::Php => php::record(ctx, exe, args, hs, out, limit),
Lang::C | Lang::Cpp => cfamily::record(ctx, exe, args, hs, out, self),
+ Lang::CSharp => csharp::record(ctx, exe, args, hs, out, limit),
}
}
@@ -134,6 +142,7 @@ impl Lang {
Lang::Go => golang::scaffold(ctx, hs, helpers, port),
Lang::Php => php::scaffold(ctx, hs, helpers, port),
Lang::C | Lang::Cpp => cfamily::scaffold(ctx, hs, helpers, port),
+ Lang::CSharp => csharp::scaffold(ctx, hs, helpers, port),
}
}
@@ -146,6 +155,7 @@ impl Lang {
Lang::Go => golang::verify(ctx, port),
Lang::Php => php::verify(ctx, port),
Lang::C | Lang::Cpp => cfamily::verify(ctx, port),
+ Lang::CSharp => csharp::verify(ctx, port),
}
}
@@ -158,6 +168,7 @@ impl Lang {
Lang::Go => golang::enable(ctx, port),
Lang::Php => php::enable(ctx, port),
Lang::C | Lang::Cpp => cfamily::enable(ctx, port),
+ Lang::CSharp => csharp::enable(ctx, port),
}
}
@@ -170,6 +181,7 @@ impl Lang {
Lang::Go => golang::disable(ctx, port),
Lang::Php => php::disable(ctx, port),
Lang::C | Lang::Cpp => cfamily::disable(ctx, port),
+ Lang::CSharp => csharp::disable(ctx, port),
}
}
@@ -180,6 +192,7 @@ impl Lang {
Lang::Go => golang::bench_command(ctx, exe),
Lang::Java => java::bench_command(ctx, exe),
Lang::C | Lang::Cpp => cfamily::bench_command(ctx, exe),
+ Lang::CSharp => csharp::bench_command(ctx, exe),
_ => Ok((exe.to_string(), ctx.state.command[1..].to_vec())),
}
}
@@ -198,7 +211,7 @@ impl Lang {
Lang::Python => format!("{ext}.abi3.so"),
Lang::Node => format!("{ext}.node"),
// loaded through a C FFI (Fiddle, FFM, ...): the platform's own library name
- Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp => built.clone(),
+ Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp => built.clone(),
};
(built, dest)
}
diff --git a/src/csharp.rs b/src/csharp.rs
new file mode 100644
index 0000000..89459c5
--- /dev/null
+++ b/src/csharp.rs
@@ -0,0 +1,594 @@
+//! C# / .NET backend: apps run as dotnet run (an SDK-style project). fast-anything builds the
+//! project once and runs the built app itself, profiled with the runtime's own EventPipe sampler
+//! (no tools to install), reads the sources with Roslyn, and calls the port through the C bridge
+//! with NativeLibrary. A small helper (src/csharp/Program.cs) is built once per machine.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::{Hotspot, Param};
+use crate::native::{self, Flavor, Patches};
+use crate::python::DISABLE_ENV;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{self, combined, output, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde::Deserialize;
+use std::collections::{HashMap, HashSet};
+use std::fs;
+use std::hash::{Hash, Hasher};
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::Instant;
+
+const TOOLS_PROJECT: &str = include_str!("csharp/Tools.csproj");
+const TOOLS_PROGRAM: &str = include_str!("csharp/Program.cs");
+const REC: &str = include_str!("csharp/Rec.cs");
+const BRIDGE: &str = include_str!("csharp/Bridge.cs");
+const JSON: &str = include_str!("csharp/Json.cs");
+
+pub fn is_csharp(program: &str) -> bool {
+ util::program_stem(program) == "dotnet"
+}
+
+pub fn resolve(program: &str, root: &Path) -> Result<String> {
+ let out = output(Command::new(program).arg("--version").current_dir(root).stdin(Stdio::null()), "dotnet")?;
+ ensure!(out.status.success(), "dotnet didn't run: install the .NET SDK (8 or newer) from https://dot.net");
+ let text = String::from_utf8_lossy(&out.stdout);
+ let major: u32 = text.trim().split('.').next().and_then(|v| v.parse().ok()).unwrap_or(0);
+ ensure!(major >= 8, "the .NET SDK 8 or newer is needed (found {})", text.trim());
+ Ok(program.to_string())
+}
+
+/// dotnet run [build options] [-- app args]
+#[derive(Debug, Default, PartialEq)]
+struct DotnetRun {
+ project: Option<String>,
+ build: Vec<String>,
+ args: Vec<String>,
+}
+
+impl DotnetRun {
+ fn parse(args: &[String]) -> Result<DotnetRun> {
+ let usage =
+ "run the app as a project: fast-anything scan -- dotnet run -c Release (or --project path/App.csproj)";
+ ensure!(args.first().map(String::as_str) == Some("run"), "{usage}");
+ let mut run = DotnetRun::default();
+ let mut i = 1;
+ while i < args.len() {
+ let a = args[i].as_str();
+ match a {
+ "--" => {
+ run.args.extend(args[i + 1..].iter().cloned());
+ break;
+ }
+ "--project" => {
+ run.project = Some(args.get(i + 1).context("--project needs a path")?.clone());
+ i += 1;
+ }
+ "-c" | "--configuration" | "-f" | "--framework" | "-r" | "--runtime" | "-a" | "--arch" => {
+ run.build.push(a.to_string());
+ run.build.push(args.get(i + 1).with_context(|| format!("{a} needs a value"))?.clone());
+ i += 1;
+ }
+ "-v" | "--verbosity" | "--launch-profile" => i += 1,
+ "--no-build" | "--no-restore" | "--no-launch-profile" => {}
+ _ if a.starts_with("-p:") || a.starts_with("--property:") || a.starts_with("/p:") => {
+ run.build.push(a.to_string())
+ }
+ _ if a.ends_with(".cs") && run.project.is_none() && run.args.is_empty() => {
+ bail!("file-based apps (dotnet run {a}) aren't supported yet: give the code a .csproj.\n{usage}")
+ }
+ _ => run.args.push(a.to_string()),
+ }
+ i += 1;
+ }
+ Ok(run)
+ }
+
+ /// The project file.
+ fn csproj(&self, root: &Path) -> Result<PathBuf> {
+ let base = self.project.as_deref().map(|p| root.join(p)).unwrap_or_else(|| root.to_path_buf());
+ if base.is_file() {
+ return Ok(base);
+ }
+ let found: Vec<PathBuf> = fs::read_dir(&base)
+ .with_context(|| format!("reading {}", base.display()))?
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|x| x == "csproj"))
+ .collect();
+ match found.as_slice() {
+ [one] => Ok(one.clone()),
+ [] => bail!("no .csproj in {} (pass --project path/App.csproj)", base.display()),
+ _ => bail!("several .csproj files in {}: pass --project path/App.csproj", base.display()),
+ }
+ }
+}
+
+/// Build the app and return the assembly dotnet runs.
+fn build(ctx: &Ctx, dotnet: &str, run: &DotnetRun) -> Result<PathBuf> {
+ let proj = run.csproj(&ctx.root)?;
+ let dotnet_cmd = |verb: &str, extra: &[&str]| {
+ let mut cmd = Command::new(dotnet);
+ cmd.arg(verb)
+ .arg(&proj)
+ .args(&run.build)
+ .args(["-nologo", "-v", "q"])
+ .args(extra)
+ .current_dir(&ctx.root)
+ .env("DOTNET_CLI_UI_LANGUAGE", "en")
+ .stdin(Stdio::null());
+ output(&mut cmd, "dotnet")
+ };
+ let built = dotnet_cmd("build", &[])?;
+ ensure!(built.status.success(), "dotnet build failed:\n{}", tail(&combined(&built), 30));
+ // -getProperty only evaluates the project; it doesn't build
+ let out = dotnet_cmd("build", &["-getProperty:TargetPath"])?;
+ ensure!(out.status.success(), "dotnet build failed:\n{}", tail(&combined(&out), 30));
+ let text = String::from_utf8_lossy(&out.stdout);
+ let target = text.lines().map(str::trim).rfind(|l| !l.is_empty()).context("dotnet build printed no TargetPath")?;
+ let target = PathBuf::from(target);
+ ensure!(target.exists(), "dotnet build said it built {}, but it isn't there", target.display());
+ Ok(target)
+}
+
+fn app_command(dotnet: &str, dll: &Path, args: &[String]) -> Command {
+ let mut cmd = Command::new(dotnet);
+ cmd.arg(dll).args(args);
+ cmd
+}
+
+pub fn bench_command(ctx: &Ctx, dotnet: &str) -> Result<(String, Vec<String>)> {
+ let run = DotnetRun::parse(&ctx.state.command[1..])?;
+ let dll = build(ctx, dotnet, &run)?;
+ let mut args = vec![dll.to_string_lossy().into_owned()];
+ args.extend(run.args);
+ Ok((dotnet.to_string(), args))
+}
+
+// ------------------------------------------------------------------ the helper (Roslyn + TraceEvent)
+
+fn cache_dir() -> PathBuf {
+ let base = std::env::var_os("LOCALAPPDATA")
+ .or_else(|| std::env::var_os("XDG_CACHE_HOME"))
+ .map(PathBuf::from)
+ .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
+ .unwrap_or_else(std::env::temp_dir);
+ base.join("fast-anything")
+}
+
+/// The helper, built on first use (it needs NuGet once, for Roslyn and TraceEvent).
+fn tools(dotnet: &str) -> Result<PathBuf> {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ (TOOLS_PROJECT, TOOLS_PROGRAM).hash(&mut h);
+ let dir = cache_dir().join(format!("cs-tools-{:016x}", h.finish()));
+ let dll = dir.join("out").join("FastAnythingTools.dll");
+ if dll.exists() {
+ return Ok(dll);
+ }
+ fs::create_dir_all(&dir)?;
+ fs::write(dir.join("Tools.csproj"), TOOLS_PROJECT)?;
+ fs::write(dir.join("Program.cs"), TOOLS_PROGRAM)?;
+ crate::ui::line(" building the C# helper (once per machine)…");
+ let out = output(
+ Command::new(dotnet)
+ .args(["build", "-c", "Release", "-nologo", "-v", "q", "-o", "out"])
+ .current_dir(&dir)
+ .stdin(Stdio::null()),
+ "dotnet",
+ )?;
+ ensure!(out.status.success(), "building the C# helper failed:\n{}", tail(&combined(&out), 30));
+ Ok(dll)
+}
+
+fn helper(ctx: &Ctx, dotnet: &str, mode: &str, input: &Path, out: &Path) -> Result<()> {
+ let run = output(
+ Command::new(dotnet)
+ .arg(tools(dotnet)?)
+ .arg(mode)
+ .arg(input)
+ .arg(out)
+ .current_dir(&ctx.root)
+ .stdin(Stdio::null()),
+ "dotnet",
+ )?;
+ ensure!(run.status.success(), "the C# helper failed ({mode}):\n{}", tail(&combined(&run), 20));
+ Ok(())
+}
+
+// ------------------------------------------------------------------ scan
+
+fn source_files(dir: &Path) -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ let Ok(entries) = fs::read_dir(&d) else { continue };
+ for e in entries.flatten() {
+ let p = e.path();
+ let name = e.file_name().to_string_lossy().into_owned();
+ if p.is_dir() {
+ if !name.starts_with('.') && !["bin", "obj", "node_modules", "target"].contains(&name.as_str()) {
+ stack.push(p);
+ }
+ } else if name.ends_with(".cs") && !name.starts_with("FastAnything") {
+ out.push(p);
+ }
+ }
+ }
+ out.sort();
+ out
+}
+
+#[derive(Deserialize, Clone)]
+struct Method {
+ class: String,
+ owner: String,
+ name: String,
+ path: PathBuf,
+ line: u32,
+ end_line: u32,
+ params: Vec<Param>,
+ returns: String,
+ blockers: Vec<String>,
+ warnings: Vec<String>,
+ calls: Vec<String>,
+ source: String,
+}
+
+#[derive(Deserialize)]
+struct Stack {
+ thread: i64,
+ frames: Vec<String>,
+ count: u64,
+}
+
+fn describe(ctx: &Ctx, dotnet: &str, dir: &Path) -> Result<Vec<Method>> {
+ let list = ctx.fast.join("cs-files.txt");
+ let files = source_files(dir);
+ ensure!(!files.is_empty(), "no .cs files in {}", dir.display());
+ fs::write(&list, files.iter().map(|f| f.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"))?;
+ let out = ctx.fast.join("cs-methods.json");
+ helper(ctx, dotnet, "describe", &list, &out)?;
+ serde_json::from_str(&fs::read_to_string(&out)?).context("reading the method list")
+}
+
+/// "Ns.Outer+Inner.Method(int32,class System.String)" -> ("Ns.Outer+Inner", "Method")
+fn split_frame(frame: &str) -> Option<(&str, &str)> {
+ let head = frame.split('(').next()?;
+ head.rsplit_once('.')
+}
+
+fn rel(ctx: &Ctx, p: &Path) -> String {
+ util::forward_slashes(p.strip_prefix(&ctx.root).unwrap_or(p))
+}
+
+pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String]) -> Result<Profile> {
+ let run = DotnetRun::parse(args)?;
+ let dll = build(ctx, dotnet, &run)?;
+ let trace_dir = ctx.fast.join("nettrace");
+ let _ = fs::remove_dir_all(&trace_dir);
+ fs::create_dir_all(&trace_dir)?;
+ let started = Instant::now();
+ let out = output(
+ app_command(dotnet, &dll, &run.args)
+ .current_dir(&ctx.root)
+ .env("DOTNET_EnableEventPipe", "1")
+ .env("DOTNET_EventPipeOutputPath", trace_dir.join("app-{pid}.nettrace"))
+ .env(
+ "DOTNET_EventPipeConfig",
+ "Microsoft-DotNETCore-SampleProfiler:0:5,Microsoft-Windows-DotNETRuntime:0x4c14fccbd:5",
+ )
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null()),
+ dotnet,
+ )?;
+ let wall = started.elapsed().as_secs_f64();
+ ensure!(out.status.success(), "the app failed ({}):\n{}", out.status, tail(&combined(&out), 30));
+ let stacks_path = ctx.fast.join("cs-stacks.json");
+ helper(ctx, dotnet, "trace", &trace_dir, &stacks_path)?;
+ let stacks: Vec<Stack> = serde_json::from_str(&fs::read_to_string(&stacks_path)?).context("reading the samples")?;
+ let _ = fs::remove_dir_all(&trace_dir);
+
+ let proj = run.csproj(&ctx.root)?;
+ let methods = describe(ctx, dotnet, proj.parent().unwrap_or(&ctx.root))?;
+ let mut by_name: HashMap<(&str, &str), usize> = HashMap::new();
+ for (i, m) in methods.iter().enumerate() {
+ by_name.entry((m.class.as_str(), m.name.as_str())).or_insert(i);
+ }
+ let resolve = |f: &str| split_frame(f).and_then(|k| by_name.get(&k).copied());
+ // threads that ran the app's own code; the runtime's idle threads don't count
+ let app_threads: HashSet<i64> =
+ stacks.iter().filter(|s| s.frames.iter().any(|f| resolve(f).is_some())).map(|s| s.thread).collect();
+ let (mut total, mut own, mut incl) = (0u64, HashMap::<usize, u64>::new(), HashMap::<usize, u64>::new());
+ for s in stacks.iter().filter(|s| app_threads.contains(&s.thread)) {
+ total += s.count;
+ let mut seen = HashSet::new();
+ for (depth, f) in s.frames.iter().enumerate() {
+ let Some(i) = resolve(f) else { continue };
+ if depth == 0 {
+ *own.entry(i).or_default() += s.count;
+ }
+ if seen.insert(i) {
+ *incl.entry(i).or_default() += s.count;
+ }
+ }
+ }
+ ensure!(total > 0, "no samples landed in the app's code: does it run long enough (a second or more)?");
+ let mut keep: Vec<usize> = incl.keys().copied().collect();
+ let helpers: Vec<usize> = keep
+ .iter()
+ .flat_map(|&i| {
+ let m = &methods[i];
+ methods
+ .iter()
+ .enumerate()
+ .filter(move |(_, h)| h.class == m.class && m.calls.contains(&h.name))
+ .map(|(j, _)| j)
+ })
+ .collect();
+ keep.extend(helpers);
+ keep.sort_unstable();
+ keep.dedup();
+ let functions = keep
+ .into_iter()
+ .map(|i| {
+ let m = &methods[i];
+ let (o, n) = (own.get(&i).copied().unwrap_or(0), incl.get(&i).copied().unwrap_or(0));
+ Hotspot {
+ file: rel(ctx, &m.path),
+ line: m.line,
+ end_line: m.end_line,
+ name: m.name.clone(),
+ qualname: m.name.clone(),
+ module: Some(m.class.replace('+', ".")),
+ kind: "function".into(),
+ tottime: o as f64 / total as f64 * wall,
+ cumtime: n as f64 / total as f64 * wall,
+ portability: if m.blockers.is_empty() { 0.9 } else { 0.0 },
+ blockers: m.blockers.clone(),
+ warnings: m.warnings.clone(),
+ params: m.params.clone(),
+ returns: Some(m.returns.clone()),
+ source: m.source.clone(),
+ calls: m.calls.clone(),
+ owner: Some(m.owner.clone()),
+ ..Hotspot::default()
+ }
+ })
+ .collect();
+ Ok(Profile { wall, base: ".".into(), functions })
+}
+
+// ------------------------------------------------------------------ editing the source
+
+/// A type as typeof() and casts accept it: no ? on reference types (string?, int[]?, List<T>?).
+fn plain_type(t: &str) -> String {
+ const VALUES: &[&str] = &[
+ "int", "long", "double", "float", "bool", "short", "byte", "sbyte", "uint", "ulong", "ushort", "char",
+ "decimal", "Int32", "Int64", "Double", "Single", "Boolean", "Int16", "Byte", "SByte", "UInt32", "UInt64",
+ "UInt16", "Char",
+ ];
+ let mut out = String::new();
+ for c in t.chars() {
+ if c == '?' {
+ let word: String = out
+ .chars()
+ .rev()
+ .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '.')
+ .collect::<Vec<_>>()
+ .into_iter()
+ .rev()
+ .collect();
+ let last = word.rsplit('.').next().unwrap_or("");
+ if VALUES.contains(&last) {
+ out.push(c);
+ }
+ continue;
+ }
+ out.push(c);
+ }
+ out
+}
+
+fn ret(hs: &Hotspot) -> String {
+ plain_type(hs.returns.as_deref().unwrap_or("object"))
+}
+
+fn args_array(hs: &Hotspot) -> String {
+ format!("new object[] {{ {} }}", hs.params.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", "))
+}
+
+fn find_body(name: &str, hint: u32) -> impl Fn(&str) -> Option<usize> {
+ let call = format!("{name}(");
+ let spaced = format!("{name} (");
+ move |text: &str| {
+ native::body_line(text, hint, |l| {
+ l.contains("static") && (l.contains(&call) || l.contains(&spaced)) && !l.trim_start().starts_with("//")
+ })
+ }
+}
+
+fn record_prologue(hs: &Hotspot) -> String {
+ let ty = |p: &Param| plain_type(p.annotation.as_deref().unwrap_or("object"));
+ let types: Vec<String> = hs.params.iter().map(|p| format!("typeof({})", ty(p))).collect();
+ let casts: Vec<String> = hs.params.iter().enumerate().map(|(i, p)| format!("({}) __faA[{i}]", ty(p))).collect();
+ format!(
+ "#nullable disable\nif (!global::FastAnythingRec.Inside)\n{{\n return ({ret}) global::FastAnythingRec.Record({args}, new global::System.Type[] {{ {types} }}, __faA => {name}({casts}));\n}}\n#nullable restore",
+ ret = ret(hs),
+ args = args_array(hs),
+ types = types.join(", "),
+ name = hs.name,
+ casts = casts.join(", "),
+ )
+}
+
+pub fn record(ctx: &Ctx, dotnet: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
+ let run = DotnetRun::parse(args)?;
+ let file = ctx.root.join(&hs.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;
+ let rec = REC.replace("/*ID*/", &hs.id).replace("/*JSON*/", JSON);
+ let patched = native::insert_in_body(
+ &text,
+ "//",
+ &format!("recording {}", hs.id),
+ &record_prologue(hs),
+ find_body(&hs.name, hs.line),
+ )?;
+ let meta = out.with_extension("meta.json");
+ let mut patches = Patches::new(ctx)?;
+ patches.write(&native::sibling(&file, "FastAnythingRec.cs")?, &rec)?;
+ patches.write(&file, &patched)?;
+ let result = build(ctx, dotnet, &run).and_then(|dll| {
+ output(
+ app_command(dotnet, &dll, &run.args)
+ .current_dir(&ctx.root)
+ .env("FAST_ANYTHING_RECORD_OUT", out)
+ .env("FAST_ANYTHING_RECORD_META", &meta)
+ .env("FAST_ANYTHING_RECORD_LIMIT", limit.to_string())
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null()),
+ dotnet,
+ )
+ });
+ patches.restore()?;
+ let ran = result?;
+ ensure!(ran.status.success(), "the app failed while recording ({}):\n{}", ran.status, tail(&combined(&ran), 30));
+ serde_json::from_str(&fs::read_to_string(&meta).context("the recorder wrote nothing")?)
+ .context("reading the recording summary")
+}
+
+// ------------------------------------------------------------------ the crate
+
+/// Rust type for a C# type.
+pub fn rust_type(t: &str) -> Option<String> {
+ let t = t.replace(' ', "").replace("System.Collections.Generic.", "").replace("System.", "");
+ if let Some(inner) = t.strip_suffix('?') {
+ return rust_type(inner).map(|r| format!("Option<{r}>"));
+ }
+ Some(match t.as_str() {
+ "int" | "Int32" => "i32".into(),
+ "long" | "Int64" => "i64".into(),
+ "short" | "Int16" => "i16".into(),
+ "sbyte" | "SByte" => "i8".into(),
+ "uint" | "UInt32" => "u32".into(),
+ "ulong" | "UInt64" => "u64".into(),
+ "ushort" | "UInt16" => "u16".into(),
+ "byte" | "Byte" => "u8".into(),
+ "double" | "Double" => "f64".into(),
+ "float" | "Single" => "f32".into(),
+ "bool" | "Boolean" => "bool".into(),
+ "char" | "Char" => "char".into(),
+ "string" | "String" => "String".into(),
+ _ if t.ends_with("[]") => format!("Vec<{}>", rust_type(&t[..t.len() - 2])?),
+ _ => {
+ let (raw, inner) = t.strip_suffix('>')?.split_once('<')?;
+ match raw {
+ "List" | "IList" | "IReadOnlyList" | "ICollection" | "IReadOnlyCollection" | "IEnumerable" => {
+ format!("Vec<{}>", rust_type(inner)?)
+ }
+ "Dictionary" | "IDictionary" | "IReadOnlyDictionary" | "SortedDictionary" => {
+ let value = inner.strip_prefix("string,").or_else(|| inner.strip_prefix("String,"))?;
+ format!("std::collections::HashMap<String, {}>", rust_type(value)?)
+ }
+ _ => return None,
+ }
+ }
+ })
+}
+
+pub const FLAVOR: Flavor = Flavor {
+ lang: backend::Lang::CSharp,
+ fence: "csharp",
+ rust_type,
+ default_json: |_| None,
+ rules: &[
+ "C# `int` is `i32` and wraps on overflow (unchecked by default): use `wrapping_*` where the original can overflow. `long` is `i64`, `byte` is `u8`.",
+ "C# strings are UTF-16: `Length` and `s[i]` count UTF-16 units. If the code indexes strings, work on `encode_utf16()` (or take a fast path when `is_ascii()`). A `char` arrives as a one-character string.",
+ "`Math.Round` rounds half to even by default: use `round_ties_even()`. `/` and `%` on integers truncate toward zero, as in Rust.",
+ "`ToLowerInvariant` maps one UTF-16 unit at a time; Rust's `to_lowercase` can differ on a few characters (İ, final sigma). `Split((char[]?)null)` splits on Unicode whitespace, like `split_whitespace`.",
+ "Arrays and lists arrive as JSON arrays, dictionaries as objects with string keys.",
+ ],
+};
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ native::scaffold(ctx, hs, helpers, port, &FLAVOR)
+}
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ native::verify(ctx, port, false)
+}
+
+// ------------------------------------------------------------------ the bridge
+
+fn bridge_class(port: &Port) -> String {
+ format!("FastAnything_{}", util::slug(&port.id))
+}
+
+fn hotspot_of<'a>(ctx: &'a Ctx, port: &Port) -> Result<&'a Hotspot> {
+ ctx.state
+ .hotspots
+ .iter()
+ .find(|h| h.id == port.id)
+ .with_context(|| format!("{} isn't in the last scan: scan again", port.id))
+}
+
+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let hs = hotspot_of(ctx, port)?;
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ let class = bridge_class(port);
+ let (_, lib) = port.lang.artifact(&port.ext);
+ let lib = util::forward_slashes(&ctx.lib_dir().join(lib));
+ let bridge = BRIDGE
+ .replace("/*CLASS*/", &class)
+ .replace("/*LIB*/", &serde_json::to_string(&lib)?)
+ .replace("/*ID*/", &port.id)
+ .replace("/*JSON*/", JSON);
+ let prologue = format!(
+ "#nullable disable\nif (global::{class}.On)\n{{\n return ({ret}) global::{class}.Call({args}, typeof({ret}));\n}}\n#nullable restore",
+ ret = ret(hs),
+ args = args_array(hs),
+ );
+ let patched = native::insert_in_body(&text, "//", &port.id, &prologue, find_body(&port.func, hs.line))?;
+ fs::write(native::sibling(&file, &format!("{class}.cs"))?, bridge)?;
+ fs::write(&file, patched).with_context(|| format!("writing {}", port.file))
+}
+
+pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
+ let file = ctx.root.join(&port.file);
+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;
+ fs::write(&file, native::strip_in_body(&text, "//", &port.id)).with_context(|| format!("writing {}", port.file))?;
+ let bridge = native::sibling(&file, &format!("{}.cs", bridge_class(port)))?;
+ if bridge.exists() {
+ fs::remove_file(bridge)?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn csharp_bits() {
+ assert_eq!(rust_type("int[][]").as_deref(), Some("Vec<Vec<i32>>"));
+ assert_eq!(rust_type("List<string>").as_deref(), Some("Vec<String>"));
+ assert_eq!(rust_type("string?").as_deref(), Some("Option<String>"));
+ assert_eq!(
+ rust_type("Dictionary<string, List<double>>").as_deref(),
+ Some("std::collections::HashMap<String, Vec<f64>>")
+ );
+ assert_eq!(rust_type("Point"), None);
+ assert_eq!(plain_type("string?"), "string");
+ assert_eq!(plain_type("int?"), "int?");
+ assert_eq!(plain_type("List<string?>?"), "List<string>");
+ assert_eq!(plain_type("System.Int32?[]?"), "System.Int32?[]");
+ assert_eq!(split_frame("Ns.Outer+Inner.Run(int32,class System.String)"), Some(("Ns.Outer+Inner", "Run")));
+ let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
+ let r = DotnetRun::parse(&s(&["run", "-c", "Release", "--project", "app", "--", "x", "-y"])).unwrap();
+ assert_eq!(r.project.as_deref(), Some("app"));
+ assert_eq!(r.build, s(&["-c", "Release"]));
+ assert_eq!(r.args, s(&["x", "-y"]));
+ assert!(DotnetRun::parse(&s(&["run", "app.cs"])).is_err());
+ assert!(DotnetRun::parse(&s(&["app.dll"])).is_err());
+ assert!(is_csharp("C:\\Program Files\\dotnet\\dotnet.exe") && !is_csharp("dotnet-trace"));
+ }
+}
diff --git a/src/csharp/Bridge.cs b/src/csharp/Bridge.cs
new file mode 100644
index 0000000..f483e41
--- /dev/null
+++ b/src/csharp/Bridge.cs
@@ -0,0 +1,58 @@
+// fast-anything: calls the verified Rust port of /*ID*/. Generated; remove with fast-anything disable /*ID*/
+// FAST_ANYTHING_DISABLE=1 runs the C# version instead.
+#nullable enable
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+using System.Runtime.InteropServices;
+
+static class /*CLASS*/
+{
+ public static readonly bool On;
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ delegate IntPtr FaCall(byte[] input, UIntPtr len, out UIntPtr outLen);
+
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ delegate void FaFree(IntPtr ptr, UIntPtr len);
+
+ static readonly FaCall? CallFn;
+ static readonly FaFree? FreeFn;
+
+ static /*CLASS*/()
+ {
+ if (Environment.GetEnvironmentVariable("FAST_ANYTHING_DISABLE") != null) return;
+ try
+ {
+ var lib = NativeLibrary.Load(/*LIB*/);
+ CallFn = Marshal.GetDelegateForFunctionPointer<FaCall>(NativeLibrary.GetExport(lib, "fa_call"));
+ FreeFn = Marshal.GetDelegateForFunctionPointer<FaFree>(NativeLibrary.GetExport(lib, "fa_free"));
+ On = true;
+ }
+ catch (Exception)
+ {
+ On = false;
+ }
+ }
+
+ public static object? Call(object?[] args, Type type)
+ {
+ byte[] input = Encoding.UTF8.GetBytes(Json.Enc(args));
+ IntPtr p = CallFn!(input, (UIntPtr)input.Length, out UIntPtr n);
+ var reply = new byte[(int)n];
+ Marshal.Copy(p, reply, 0, reply.Length);
+ FreeFn!(p, n);
+ using var doc = JsonDocument.Parse(reply);
+ if (doc.RootElement.TryGetProperty("error", out var e)) throw new InvalidOperationException("fast-anything: " + e);
+ return JsonSerializer.Deserialize(doc.RootElement.GetProperty("ok"), type, Json.Options);
+ }
+
+/*JSON*/
+}
diff --git a/src/csharp/Json.cs b/src/csharp/Json.cs
new file mode 100644
index 0000000..8d066d3
--- /dev/null
+++ b/src/csharp/Json.cs
@@ -0,0 +1,138 @@
+ // ---- JSON, shared by the recorder and the bridge (generated by fast-anything)
+ internal static class Json
+ {
+ internal sealed class Unsupported : Exception
+ {
+ public Unsupported(string m) : base(m) { }
+ }
+
+ public static readonly JsonSerializerOptions Options = MakeOptions();
+
+ static JsonSerializerOptions MakeOptions()
+ {
+ var o = new JsonSerializerOptions();
+ o.Converters.Add(new BytesAsNumbers());
+ return o;
+ }
+
+ // byte[] travels as a list of numbers, like every other array (System.Text.Json would use base64)
+ sealed class BytesAsNumbers : JsonConverter<byte[]>
+ {
+ public override byte[]? Read(ref Utf8JsonReader r, Type t, JsonSerializerOptions o)
+ {
+ if (r.TokenType == JsonTokenType.Null) return null;
+ var bytes = new List<byte>();
+ while (r.Read() && r.TokenType != JsonTokenType.EndArray) bytes.Add(r.GetByte());
+ return bytes.ToArray();
+ }
+
+ public override void Write(Utf8JsonWriter w, byte[] v, JsonSerializerOptions o)
+ {
+ w.WriteStartArray();
+ foreach (var b in v) w.WriteNumberValue(b);
+ w.WriteEndArray();
+ }
+ }
+
+ public static object? Dec(JsonNode? n, Type t) => n is null ? null : JsonSerializer.Deserialize(n, t, Options);
+
+ public static string Enc(object? v)
+ {
+ var b = new StringBuilder();
+ Enc(v, b);
+ return b.ToString();
+ }
+
+ static void Number(string s, StringBuilder b)
+ {
+ b.Append(s);
+ if (s.IndexOfAny(new[] { '.', 'E', 'e' }) < 0) b.Append(".0");
+ }
+
+ static void Enc(object? v, StringBuilder b)
+ {
+ var inv = CultureInfo.InvariantCulture;
+ switch (v)
+ {
+ case null: b.Append("null"); break;
+ case bool x: b.Append(x ? "true" : "false"); break;
+ case string s: Str(s, b); break;
+ case char c: Str(c.ToString(), b); break;
+ case int or long or short or sbyte or byte or uint or ulong or ushort:
+ b.Append(((IFormattable)v).ToString(null, inv));
+ break;
+ case double d:
+ if (!double.IsFinite(d)) throw new Unsupported("NaN or Infinity");
+ Number(d.ToString("R", inv), b);
+ break;
+ case float f:
+ if (!float.IsFinite(f)) throw new Unsupported("NaN or Infinity");
+ Number(f.ToString("R", inv), b);
+ break;
+ case IDictionary m:
+ {
+ b.Append('{');
+ bool first = true;
+ foreach (DictionaryEntry e in m)
+ {
+ if (e.Key is not string k) throw new Unsupported("Dictionary with non-string keys");
+ if (!first) b.Append(',');
+ first = false;
+ Str(k, b);
+ b.Append(':');
+ Enc(e.Value, b);
+ }
+ b.Append('}');
+ break;
+ }
+ case IEnumerable xs:
+ {
+ b.Append('[');
+ bool first = true;
+ foreach (var x in xs)
+ {
+ if (!first) b.Append(',');
+ first = false;
+ Enc(x, b);
+ }
+ b.Append(']');
+ break;
+ }
+ default: throw new Unsupported(v.GetType().Name);
+ }
+ }
+
+ public static void Str(string s, StringBuilder b)
+ {
+ b.Append('"');
+ for (int i = 0; i < s.Length; i++)
+ {
+ char c = s[i];
+ if (char.IsHighSurrogate(c) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]))
+ {
+ b.Append(c).Append(s[++i]);
+ continue;
+ }
+ if (char.IsSurrogate(c)) throw new Unsupported("string with a lone surrogate");
+ switch (c)
+ {
+ case '"': b.Append("\\\""); break;
+ case '\\': b.Append("\\\\"); break;
+ case '\n': b.Append("\\n"); break;
+ case '\r': b.Append("\\r"); break;
+ case '\t': b.Append("\\t"); break;
+ default:
+ if (c < 0x20) b.Append("\\u").Append(((int)c).ToString("x4")); else b.Append(c);
+ break;
+ }
+ }
+ b.Append('"');
+ }
+
+ public static string Str(string s)
+ {
+ var b = new StringBuilder();
+ Str(s, b);
+ return b.ToString();
+ }
+ }
diff --git a/src/csharp/Program.cs b/src/csharp/Program.cs
new file mode 100644
index 0000000..6b1d08e
--- /dev/null
+++ b/src/csharp/Program.cs
@@ -0,0 +1,236 @@
+// C# side of fast-anything's scan. The CLI runs it as
+// FastAnythingTools describe <file list> <out.json> every method in the app's sources (Roslyn)
+// FastAnythingTools trace <dir> <out.json> sampled stacks from the .nettrace files in dir
+// Not meant to be run by hand.
+using System.Text;
+using System.Text.Json;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.Diagnostics.Tracing;
+using Microsoft.Diagnostics.Tracing.Etlx;
+
+static class Tools
+{
+ static int Main(string[] args)
+ {
+ if (args.Length != 3) { Console.Error.WriteLine("usage: describe|trace <in> <out>"); return 2; }
+ object result = args[0] switch
+ {
+ "describe" => Describe.Run(File.ReadAllLines(args[1]).Where(l => l.Trim().Length > 0).Select(l => l.Trim())),
+ "trace" => Trace.Run(args[1]),
+ _ => throw new ArgumentException(args[0]),
+ };
+ File.WriteAllText(args[2], JsonSerializer.Serialize(result), new UTF8Encoding(false));
+ return 0;
+ }
+}
+
+static class Trace
+{
+ public static object Run(string dir)
+ {
+ var stacks = new Dictionary<string, (int thread, List<string> frames, int count)>();
+ int files = 0;
+ foreach (var path in Directory.GetFiles(dir, "*.nettrace"))
+ {
+ files++;
+ var etlx = Path.ChangeExtension(path, ".etlx");
+ using var log = new TraceLog(TraceLog.CreateFromEventPipeDataFile(path, etlx));
+ foreach (var ev in log.Events)
+ {
+ if (ev.ProviderName != "Microsoft-DotNETCore-SampleProfiler") continue;
+ var frames = new List<string>();
+ for (var cs = ev.CallStack(); cs != null; cs = cs.Caller)
+ {
+ var m = cs.CodeAddress.Method;
+ if (m != null) frames.Add(m.FullMethodName);
+ }
+ if (frames.Count == 0) continue;
+ int thread = ev.ThreadID + 1_000_000 * files;
+ var key = thread + "|" + string.Join("|", frames);
+ stacks[key] = stacks.TryGetValue(key, out var s) ? (s.thread, s.frames, s.count + 1) : (thread, frames, 1);
+ }
+ }
+ return stacks.Values.Select(s => new { thread = s.thread, frames = s.frames, count = s.count }).ToList();
+ }
+}
+
+static class Describe
+{
+ static readonly HashSet<string> Io = ["Console", "File", "Directory", "Path", "FileInfo", "DirectoryInfo", "FileStream",
+ "StreamReader", "StreamWriter", "HttpClient", "WebClient", "Socket", "TcpClient", "Process", "Thread", "Task",
+ "Parallel", "ThreadPool", "Environment", "Debug", "Trace", "Logger", "ILogger", "Registry", "Timer"];
+ static readonly HashSet<string> NondetCalls = ["Guid.NewGuid", "Random.Shared", "Stopwatch.StartNew", "Stopwatch.GetTimestamp",
+ "DateTime.Now", "DateTime.UtcNow", "DateTimeOffset.Now", "DateTimeOffset.UtcNow", "DateTime.Today", "Environment.TickCount",
+ "Environment.TickCount64", "RandomNumberGenerator"];
+ static readonly HashSet<string> NondetNew = ["Random", "Stopwatch"];
+ static readonly HashSet<string> Scalars = ["int", "long", "double", "float", "bool", "short", "byte", "sbyte", "uint",
+ "ulong", "ushort", "char", "string", "Int32", "Int64", "Double", "Single", "Boolean", "Int16", "Byte", "SByte",
+ "UInt32", "UInt64", "UInt16", "Char", "String"];
+ static readonly HashSet<string> Lists = ["List", "IList", "IReadOnlyList", "ICollection", "IReadOnlyCollection", "IEnumerable"];
+ static readonly HashSet<string> Maps = ["Dictionary", "IDictionary", "IReadOnlyDictionary", "SortedDictionary"];
+
+ public static object Run(IEnumerable<string> files)
+ {
+ var methods = new List<object>();
+ foreach (var path in files)
+ {
+ var src = File.ReadAllText(path);
+ var tree = CSharpSyntaxTree.ParseText(src, path: path);
+ var lines = src.Replace("\r", "").Split('\n');
+ foreach (var type in tree.GetRoot().DescendantNodes().OfType<TypeDeclarationSyntax>())
+ foreach (var m in type.Members.OfType<MethodDeclarationSyntax>())
+ methods.Add(Method(m, type, tree, lines));
+ }
+ return methods;
+ }
+
+ static string Ns(SyntaxNode n)
+ {
+ var parts = n.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().Select(x => x.Name.ToString()).Reverse();
+ return string.Join(".", parts);
+ }
+
+ public static bool Supported(string t)
+ {
+ t = t.Replace(" ", "").Replace("System.Collections.Generic.", "").Replace("System.", "");
+ if (t.EndsWith("?")) t = t[..^1];
+ if (Scalars.Contains(t)) return true;
+ if (t.EndsWith("[]")) return Supported(t[..^2]);
+ int lt = t.IndexOf('<');
+ if (lt < 0 || !t.EndsWith(">")) return false;
+ string raw = t[..lt], inner = t[(lt + 1)..^1];
+ if (Lists.Contains(raw)) return Supported(inner);
+ if (Maps.Contains(raw) && (inner.StartsWith("string,") || inner.StartsWith("String,"))) return Supported(inner[(inner.IndexOf(',') + 1)..]);
+ return false;
+ }
+
+ static object Method(MethodDeclarationSyntax m, TypeDeclarationSyntax type, SyntaxTree tree, string[] lines)
+ {
+ var chain = m.Ancestors().OfType<TypeDeclarationSyntax>().Reverse().Select(t => t.Identifier.Text).ToList();
+ string ns = Ns(type);
+ string cls = (ns.Length > 0 ? ns + "." : "") + string.Join("+", chain);
+ string name = m.Identifier.Text;
+ var mods = m.Modifiers.Select(x => x.Text).ToHashSet();
+ var blockers = new List<string>();
+ var warnings = new List<string>();
+ if (!mods.Contains("static")) blockers.Add("instance method (static methods only for now)");
+ if (name == "Main") blockers.Add("the entry point");
+ if (m.TypeParameterList != null) blockers.Add("generic method");
+ if (m.Ancestors().OfType<TypeDeclarationSyntax>().Any(t => t.TypeParameterList != null)) blockers.Add("in a generic class");
+ if (mods.Contains("async")) blockers.Add("async");
+ if (mods.Contains("unsafe") || mods.Contains("extern") || mods.Contains("partial")) blockers.Add(string.Join(" ", mods.Intersect(["unsafe", "extern", "partial"])));
+ if (m.Body == null) blockers.Add(m.ExpressionBody != null ? "expression-bodied (give it a { } body)" : "has no body");
+ string returns = m.ReturnType.ToString();
+ if (returns == "void") blockers.Add("returns nothing (void)");
+ else if (!Supported(returns)) blockers.Add("returns a " + returns);
+ var parms = new List<object>();
+ var locals = new HashSet<string>();
+ foreach (var p in m.ParameterList.Parameters)
+ {
+ string t = p.Type?.ToString() ?? "?";
+ var pm = p.Modifiers.Select(x => x.Text).ToList();
+ if (pm.Contains("ref") || pm.Contains("out") || pm.Contains("in")) blockers.Add($"takes {string.Join(" ", pm)} {t}");
+ else if (pm.Contains("params")) blockers.Add("takes params");
+ else if (pm.Contains("this")) blockers.Add("extension method");
+ else if (!Supported(t)) blockers.Add("takes a " + t);
+ locals.Add(p.Identifier.Text);
+ parms.Add(new { name = p.Identifier.Text, annotation = t, @default = p.Default?.Value.ToString() });
+ }
+ var fields = type.Members.OfType<FieldDeclarationSyntax>().SelectMany(f => f.Declaration.Variables.Select(v => v.Identifier.Text))
+ .Concat(type.Members.OfType<PropertyDeclarationSyntax>().Select(p => p.Identifier.Text)).ToHashSet();
+ var statics = type.Members.OfType<MethodDeclarationSyntax>().Where(x => x.Modifiers.Any(t => t.Text == "static"))
+ .Select(x => x.Identifier.Text).ToHashSet();
+ var io = new List<string>();
+ var nondet = new List<string>();
+ var helpers = new List<string>();
+ bool writesStatic = false;
+ SyntaxNode? body = (SyntaxNode?)m.Body ?? m.ExpressionBody;
+ if (body != null)
+ {
+ foreach (var n in body.DescendantNodes())
+ {
+ switch (n)
+ {
+ case VariableDeclaratorSyntax v: locals.Add(v.Identifier.Text); break;
+ case SingleVariableDesignationSyntax d: locals.Add(d.Identifier.Text); break;
+ case ForEachStatementSyntax f: locals.Add(f.Identifier.Text); break;
+ }
+ }
+ foreach (var n in body.DescendantNodes())
+ {
+ if (n is MemberAccessExpressionSyntax ma)
+ {
+ string s = ma.ToString().Replace("System.", "");
+ string head = ma.Expression.ToString().Replace("System.", "");
+ head = head.Contains('.') ? head[(head.LastIndexOf('.') + 1)..] : head;
+ if (Io.Contains(head) && !locals.Contains(head)) Add(io, s);
+ if (NondetCalls.Contains(s) || NondetCalls.Contains(head)) Add(nondet, s);
+ }
+ if (n is ObjectCreationExpressionSyntax oc)
+ {
+ string t = oc.Type.ToString();
+ t = t.Contains('<') ? t[..t.IndexOf('<')] : t;
+ t = t.Contains('.') ? t[(t.LastIndexOf('.') + 1)..] : t;
+ if (NondetNew.Contains(t)) Add(nondet, "new " + t);
+ if (Io.Contains(t)) Add(io, "new " + t);
+ }
+ if (n is InvocationExpressionSyntax inv)
+ {
+ string callee = inv.Expression switch
+ {
+ IdentifierNameSyntax id => id.Identifier.Text,
+ MemberAccessExpressionSyntax ma2 when ma2.Expression.ToString() == type.Identifier.Text => ma2.Name.Identifier.Text,
+ _ => "",
+ };
+ if (callee.Length > 0 && callee != name && statics.Contains(callee)) Add(helpers, callee);
+ }
+ ExpressionSyntax? target = n switch
+ {
+ AssignmentExpressionSyntax a => a.Left,
+ PrefixUnaryExpressionSyntax u when u.IsKind(SyntaxKind.PreIncrementExpression) || u.IsKind(SyntaxKind.PreDecrementExpression) => u.Operand,
+ PostfixUnaryExpressionSyntax u => u.Operand,
+ _ => null,
+ };
+ if (target is IdentifierNameSyntax tid && fields.Contains(tid.Identifier.Text) && !locals.Contains(tid.Identifier.Text)) writesStatic = true;
+ if (target is MemberAccessExpressionSyntax tma && tma.Expression.ToString() == type.Identifier.Text && fields.Contains(tma.Name.Identifier.Text)) writesStatic = true;
+ if (target is ElementAccessExpressionSyntax ea && ea.Expression is IdentifierNameSyntax eid && fields.Contains(eid.Identifier.Text) && !locals.Contains(eid.Identifier.Text)) writesStatic = true;
+ }
+ }
+ if (io.Count > 0) blockers.Add("does I/O: " + string.Join(", ", io.Take(3)));
+ if (nondet.Count > 0) blockers.Add("not deterministic: " + string.Join(", ", nondet.Take(3)));
+ if (writesStatic) blockers.Add("writes static fields");
+ if (helpers.Count > 0) warnings.Add("calls " + string.Join(", ", helpers.Take(3)) + ", they get ported together with it");
+ if (m.Body != null)
+ {
+ var open = m.Body.OpenBraceToken;
+ var openLine = tree.GetLineSpan(open.Span).StartLinePosition.Line;
+ var firstInside = m.Body.Statements.FirstOrDefault();
+ var closeLine = tree.GetLineSpan(m.Body.CloseBraceToken.Span).StartLinePosition.Line;
+ if ((firstInside != null && tree.GetLineSpan(firstInside.Span).StartLinePosition.Line == openLine) || closeLine == openLine)
+ blockers.Add("its { doesn't end a line (put the body on its own lines)");
+ }
+ var span = tree.GetLineSpan(m.Span);
+ int line = tree.GetLineSpan(m.Identifier.Span).StartLinePosition.Line + 1;
+ int start = span.StartLinePosition.Line, end = span.EndLinePosition.Line;
+ string source = string.Join("\n", lines[start..Math.Min(end + 1, lines.Length)]).TrimEnd();
+ return new
+ {
+ @class = cls,
+ owner = string.Join(".", chain),
+ name,
+ path = tree.FilePath,
+ line,
+ end_line = end + 1,
+ @params = parms,
+ returns,
+ blockers,
+ warnings,
+ calls = helpers,
+ source,
+ };
+ }
+
+ static void Add(List<string> xs, string s) { if (!xs.Contains(s)) xs.Add(s); }
+}
diff --git a/src/csharp/Rec.cs b/src/csharp/Rec.cs
new file mode 100644
index 0000000..77f5971
--- /dev/null
+++ b/src/csharp/Rec.cs
@@ -0,0 +1,281 @@
+// fast-anything: records calls to /*ID*/ for one run. Generated; removed when the run ends.
+#nullable enable
+#pragma warning disable
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+
+static class FastAnythingRec
+{
+ public static bool Inside;
+ static readonly object Gate = new();
+ static readonly int Limit = int.TryParse(Environment.GetEnvironmentVariable("FAST_ANYTHING_RECORD_LIMIT"), out var n) ? n : 500;
+ static readonly Random Rng = new(0xFA57);
+ static readonly List<string> Kept = new();
+ static readonly List<string?> KeptArgs = new();
+ static readonly List<string> Unsupported = new();
+ static long Calls, Skipped, Ticks;
+ static Func<object?[], object?>? Fn;
+ static Type[] Types = Array.Empty<Type>();
+ static readonly string[] Texts = { "", "ÀÉÎõü ñ", "日本語のテキスト", "emoji 👍🏽🎉", "é́", "İ ß Dž ΣΑΣ" };
+ static readonly int[] Slices = { 0, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
+
+ static FastAnythingRec()
+ {
+ AppDomain.CurrentDomain.ProcessExit += (_, _) => Save();
+ }
+
+ static void Note(string what)
+ {
+ if (!Unsupported.Contains(what)) Unsupported.Add(what);
+ }
+
+ public static object? Record(object?[] args, Type[] types, Func<object?[], object?> f)
+ {
+ lock (Gate)
+ {
+ Fn = f;
+ Types = types;
+ Inside = true;
+ try
+ {
+ Calls++;
+ int slot = Kept.Count < Limit ? Kept.Count : (int)(Rng.NextDouble() * Calls);
+ string? a = null;
+ if (slot < Limit)
+ {
+ try { a = Json.Enc(args); }
+ catch (Json.Unsupported e) { Skipped++; Note(e.Message); }
+ }
+ long t = Stopwatch.GetTimestamp();
+ object? r;
+ try
+ {
+ r = f(args);
+ }
+ catch (Exception e)
+ {
+ Ticks += Stopwatch.GetTimestamp() - t;
+ if (a != null) Store(slot, "{\"args\":" + a + ",\"raises\":" + Json.Str(e.GetType().FullName ?? "Exception") + "}", null);
+ throw;
+ }
+ Ticks += Stopwatch.GetTimestamp() - t;
+ if (a != null)
+ {
+ try { Store(slot, "{\"args\":" + a + ",\"result\":" + Json.Enc(r) + "}", a); }
+ catch (Json.Unsupported e) { Skipped++; Note(e.Message); }
+ }
+ return r;
+ }
+ finally
+ {
+ Inside = false;
+ }
+ }
+ }
+
+ static void Store(int slot, string line, string? args)
+ {
+ if (slot < Kept.Count)
+ {
+ Kept[slot] = line;
+ KeptArgs[slot] = args;
+ }
+ else
+ {
+ Kept.Add(line);
+ KeptArgs.Add(args);
+ }
+ }
+
+ static Type Element(Type t)
+ {
+ t = Nullable.GetUnderlyingType(t) ?? t;
+ if (t.IsArray) return t.GetElementType()!;
+ return t.IsGenericType ? t.GetGenericArguments()[^1] : typeof(object);
+ }
+
+ // Special values for one argument: zero and ±1, -0.0, non-ASCII text, empty collections.
+ static IEnumerable<JsonNode?> Edges(JsonNode? v, Type t)
+ {
+ var u = Nullable.GetUnderlyingType(t) ?? t;
+ if (u == typeof(string)) foreach (var s in Texts) yield return JsonValue.Create(s);
+ else if (u == typeof(char)) foreach (var s in new[] { "a", "é", "日", " " }) yield return JsonValue.Create(s);
+ else if (u == typeof(bool)) { yield return JsonValue.Create(true); yield return JsonValue.Create(false); }
+ else if (u == typeof(double) || u == typeof(float)) foreach (var d in new[] { 0.0, -0.0, 1.0, -1.0, 0.5 }) yield return JsonValue.Create(d);
+ else if (u.IsPrimitive) foreach (var i in new[] { 0, 1, -1 }) yield return JsonValue.Create(i);
+ else if (v is JsonArray arr)
+ {
+ yield return new JsonArray();
+ var inner = Element(t);
+ if (inner == typeof(string)) yield return new JsonArray(Texts.Select(s => (JsonNode?)JsonValue.Create(s)).ToArray());
+ if (arr.Count > 0) foreach (var e in Edges(arr[0], inner)) yield return new JsonArray(e?.DeepClone());
+ }
+ else if (v is JsonObject) yield return new JsonObject();
+ if (Nullable.GetUnderlyingType(t) != null) yield return null;
+ }
+
+ // The same input, much bigger: 4x, 16x, ... up to 4096 items or characters.
+ static JsonNode? Bigger(JsonNode? v, int factor)
+ {
+ if (v is JsonArray a && a.Count > 0)
+ {
+ int n = Math.Min(4096, a.Count * factor);
+ if (n <= a.Count) return null;
+ var big = new JsonArray();
+ for (int i = 0; i < n; i++) big.Add(a[i % a.Count]?.DeepClone());
+ return big;
+ }
+ if (v is JsonValue s && s.TryGetValue<string>(out var text) && text.Length > 0)
+ {
+ int n = Math.Min(4096, text.Length * factor);
+ if (n <= text.Length) return null;
+ var b = new StringBuilder();
+ while (b.Length < n) b.Append(text);
+ return JsonValue.Create(b.ToString());
+ }
+ return null;
+ }
+
+ // A short version of a recorded value, so edge cases stay cheap when the real inputs are big.
+ static JsonNode? Small(JsonNode? v)
+ {
+ if (v is JsonArray a) return new JsonArray(a.Take(8).Select(Small).ToArray());
+ if (v is JsonValue s && s.TryGetValue<string>(out var text))
+ {
+ var runes = text.EnumerateRunes().Take(32).Select(r => r.ToString());
+ return JsonValue.Create(string.Concat(runes));
+ }
+ return v?.DeepClone();
+ }
+
+ // Shorter slices of a string or collection, for the shrunk "derived" cases.
+ static IEnumerable<JsonNode?> Variants(JsonNode? v)
+ {
+ if (v is JsonValue s && s.TryGetValue<string>(out var text))
+ {
+ var runes = new List<string>();
+ foreach (var r in text.EnumerateRunes()) runes.Add(r.ToString());
+ int n = runes.Count;
+ if (n < 2) yield break;
+ foreach (int len in Slices)
+ {
+ if (len >= n) yield break;
+ for (int rep = 0; rep < (len < 2 ? 1 : 3); rep++)
+ {
+ int off = Rng.Next(n - len + 1);
+ yield return JsonValue.Create(string.Concat(runes.GetRange(off, len)));
+ }
+ }
+ }
+ else if (v is JsonArray a && a.Count >= 2)
+ {
+ foreach (int len in Slices)
+ {
+ if (len >= a.Count) yield break;
+ for (int rep = 0; rep < (len < 2 ? 1 : 3); rep++)
+ {
+ int off = Rng.Next(a.Count - len + 1);
+ var part = new JsonArray();
+ for (int i = off; i < off + len; i++) part.Add(a[i]?.DeepClone());
+ yield return part;
+ }
+ }
+ }
+ }
+
+ // Runs the original on args with argument i replaced; keeps the case. Seconds it took, or -1.
+ static double Try(JsonArray args, int i, JsonNode? value, string tag, List<string> derived, HashSet<string> seen)
+ {
+ var next = (JsonArray)args.DeepClone();
+ next[i] = value?.DeepClone();
+ if (!seen.Add(next.ToJsonString())) return -1;
+ try
+ {
+ var objs = new object?[next.Count];
+ for (int k = 0; k < next.Count; k++) objs[k] = Json.Dec(next[k], Types[k]);
+ string a = Json.Enc(objs);
+ long t = Stopwatch.GetTimestamp();
+ var r = Fn!(objs);
+ double took = (Stopwatch.GetTimestamp() - t) / (double)Stopwatch.Frequency;
+ derived.Add("{\"args\":" + a + ",\"result\":" + Json.Enc(r) + ",\"derived\":" + tag + "}");
+ return took;
+ }
+ catch (Exception)
+ {
+ return -1; // outside the function's domain: not a fair test
+ }
+ }
+
+ static void Save()
+ {
+ lock (Gate)
+ {
+ Inside = true;
+ var derived = new List<string>();
+ var seen = new HashSet<string>();
+ var clock = Stopwatch.StartNew();
+ var cases = new List<JsonArray>();
+ foreach (var a in KeptArgs) if (a != null && JsonNode.Parse(a) is JsonArray arr) cases.Add(arr);
+ if (Fn != null)
+ {
+ double Left() => 1.5 - clock.Elapsed.TotalSeconds;
+ var grown = new HashSet<int>();
+ foreach (var recorded in cases.Take(20))
+ {
+ var args = new JsonArray(recorded.Select(Small).ToArray());
+ for (int i = 0; i < args.Count && i < Types.Length; i++)
+ {
+ foreach (var e in Edges(args[i], Types[i]))
+ {
+ if (derived.Count >= 100 || Left() <= 0) goto shrink;
+ Try(args, i, e, "\"edge\"", derived, seen);
+ }
+ if (!grown.Add(i)) continue;
+ double took = 0;
+ foreach (int factor in new[] { 4, 16, 64, 256, 1024 })
+ {
+ var big = Bigger(args[i], factor);
+ if (big == null || derived.Count >= 100 || took * 16 > Left() / 2) break;
+ took = Try(args, i, big, "\"edge\"", derived, seen);
+ if (took < 0) break;
+ }
+ }
+ }
+ shrink:
+ int edges = derived.Count;
+ foreach (var args in cases)
+ {
+ for (int i = 0; i < args.Count && i < Types.Length; i++)
+ {
+ foreach (var smaller in Variants(args[i]))
+ {
+ if (derived.Count >= 200 + edges || clock.Elapsed.TotalSeconds > 3) goto write;
+ Try(args, i, smaller, "true", derived, seen);
+ }
+ }
+ }
+ }
+ write:
+ var b = new StringBuilder();
+ foreach (var line in Kept) b.Append(line).Append('\n');
+ foreach (var line in derived) b.Append(line).Append('\n');
+ System.IO.File.WriteAllText(Environment.GetEnvironmentVariable("FAST_ANYTHING_RECORD_OUT")!, b.ToString(), new UTF8Encoding(false));
+ var u = new StringBuilder("[");
+ foreach (var s in Unsupported) u.Append(u.Length > 1 ? "," : "").Append(Json.Str(s));
+ double ns = Calls > 0 ? Ticks * 1e9 / Stopwatch.Frequency / Calls : 0;
+ string meta = "{\"calls\":" + Calls + ",\"kept\":" + Kept.Count + ",\"skipped\":" + Skipped + ",\"unsupported\":" + u + "]"
+ + ",\"original_ns\":" + ns.ToString("R", CultureInfo.InvariantCulture) + "}";
+ System.IO.File.WriteAllText(Environment.GetEnvironmentVariable("FAST_ANYTHING_RECORD_META")!, meta, new UTF8Encoding(false));
+ }
+ }
+
+/*JSON*/
+}
diff --git a/src/csharp/Tools.csproj b/src/csharp/Tools.csproj
new file mode 100644
index 0000000..36b254b
--- /dev/null
+++ b/src/csharp/Tools.csproj
@@ -0,0 +1,16 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <!-- fast-anything's C# helper: reads sources with Roslyn and EventPipe traces with TraceEvent. Built into .fast once per project. -->
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net8.0</TargetFramework>
+ <RollForward>Major</RollForward>
+ <Nullable>enable</Nullable>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <AssemblyName>FastAnythingTools</AssemblyName>
+ <NoWarn>$(NoWarn);CS8600;CS8602;CS8604</NoWarn>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="5.0.0" />
+ <PackageReference Include="Microsoft.Diagnostics.Tracing.TraceEvent" Version="3.2.8" />
+ </ItemGroup>
+</Project>
diff --git a/src/doctor.rs b/src/doctor.rs
index 3b00763..6f987bd 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -59,6 +59,12 @@ pub fn run() -> Result<()> {
need: "for C/C++ apps (or gcc)",
hint: "https://llvm.org",
},
+ Check {
+ name: "dotnet",
+ found: version("dotnet", &["--version"]),
+ need: "for C# apps (.NET SDK 8+)",
+ hint: "https://dot.net",
+ },
Check {
name: "claude",
found: version("claude", &["--version"]),
@@ -88,8 +94,8 @@ pub fn run() -> Result<()> {
}
ensure!(checks[0].found.is_some(), "Rust is needed to build ports");
ensure!(
- checks[1..8].iter().any(|c| c.found.is_some()),
- "install Python, Node.js, Ruby, Java, Go, PHP or a C compiler"
+ checks[1..9].iter().any(|c| c.found.is_some()),
+ "install Python, Node.js, Ruby, Java, Go, PHP, .NET or a C compiler"
);
ui::ok("ready");
Ok(())
diff --git a/src/main.rs b/src/main.rs
index f03431a..4c8cca7 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -4,6 +4,7 @@ mod agent;
mod backend;
mod bench;
mod cfamily;
+mod csharp;
mod doctor;
mod golang;
mod hotspot;
diff --git a/src/mcp.rs b/src/mcp.rs
index d6116ff..88c3805 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -8,7 +8,7 @@ use std::path::PathBuf;
const PROTOCOL: &str = "2025-06-18";
-const INSTRUCTIONS: &str = "fast-anything speeds up Python, Node.js, Ruby, Java, Go, PHP, C and C++ apps by porting their hottest pure functions to Rust (PyO3 / napi-rs / a C ABI bridge) \
+const INSTRUCTIONS: &str = "fast-anything speeds up Python, Node.js, Ruby, Java, Go, PHP, C, C++ and C# apps by porting their hottest pure functions to Rust (PyO3 / napi-rs / a C ABI bridge) \
and proving the port gives the same results on real recorded calls. Loop: fast_scan -> fast_port -> write src/lib.rs \
following the returned task -> fast_verify (repeat until it passes) -> fast_enable -> fast_bench -> fast_report.";
diff --git a/src/native.rs b/src/native.rs
index fad53db..459eb89 100644
--- a/src/native.rs
+++ b/src/native.rs
@@ -1,5 +1,5 @@
//! The bridge shared by every language that calls its port through a C entry point (Ruby, Go,
-//! PHP, Java): the crate (JSON in, JSON out), the replay check, temporary edits that always get
+//! PHP, Java, C#): the crate (JSON in, JSON out), the replay check, temporary edits that always get
//! undone, and the blocks fast-anything puts inside a function's body.
//!
//! Go, PHP and Java record differently from Python and Node: a few lines at the top of the hot