Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
Maven and Gradle builds for Java; C and C++ backend
EL4CTEO1dec0cfdbcfc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b29af46..f788238 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -42,6 +42,7 @@ jobs:with:go-version: stablecache: false+ - uses: gradle/actions/setup-gradle@v6- uses: Swatinem/rust-cache@v2- run: cargo fmt --check- run: cargo clippy --all-targets -- -D warnings@@ -129,3 +130,56 @@ jobs:$fa disablegit diff --exit-code fuzzy.phptest -z "$(git status --porcelain .)"+ - name: end to end, Java with Maven+ working-directory: examples/fuzzy-dedupe-java-build+ run: |+ fa=../../target/release/fast-anything+ $fa scan -- mvn -q compile exec:java+ $fa port+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs+ $fa verify+ $fa enable+ mvn -q compile exec:java+ $fa bench --runs 2+ $fa disable+ git diff --exit-code src+ rm -rf .fast target+ - name: end to end, Java with Gradle+ working-directory: examples/fuzzy-dedupe-java-build+ run: |+ fa=../../target/release/fast-anything+ $fa scan -- gradle -q run+ $fa port+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs+ $fa verify+ $fa enable+ gradle -q --no-daemon run+ $fa bench --runs 2+ $fa disable+ git diff --exit-code src+ - name: end to end, C+ working-directory: examples/mandelbrot-c+ run: |+ fa=../../target/release/fast-anything+ $fa scan -- clang -O2 main.c mandelbrot.c+ $fa port+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs+ $fa verify+ $fa enable+ clang -O2 main.c mandelbrot.c -o app && ./app+ $fa bench --runs 2+ $fa disable+ git diff --exit-code mandelbrot.c+ - name: end to end, C+++ working-directory: examples/fuzzy-dedupe-cpp+ run: |+ fa=../../target/release/fast-anything+ $fa scan -- clang++ -O2 -std=c++17 main.cpp fuzzy.cpp+ $fa port+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs+ $fa verify+ $fa enable+ clang++ -O2 -std=c++17 main.cpp fuzzy.cpp -o app && ./app+ $fa bench --runs 2+ $fa disable+ git diff --exit-code fuzzy.cppdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1473224..b005158 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- Java apps built with Maven (`mvn -q compile exec:java`) or Gradle (`gradle -q run`): sources come from `src/main/java`, every JVM the build starts is profiled, and Gradle runs without its daemon.+## 0.3.0- PHP (8.1+): apps run as `php app.php`. Profiled with a one-line timer per function for one run, parsed with PHP's tokenizer, ports called through the FFI extension.diff --git a/README.md b/README.mdindex 6e99bcd..e44c6c2 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ Ports are compiled with your Rust toolchain ([rustup](https://rustup.rs)).## Use```sh-fast-anything go --agent claude -- python app.py # or: -- node app.ts / ruby app.rb / java App.java / go run . / php app.php+fast-anything go --agent claude -- python app.py # or: -- node app.ts / ruby app.rb / java App.java / mvn exec:java / gradle run / go run . / php app.php```Or step by step:@@ -88,7 +88,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi| Python 3.10+ | PyO3 | ✅ || JavaScript / TypeScript (Node 22+) | napi-rs | ✅ || Ruby 3.3+ | C ABI + JSON, through Ruby's built-in Fiddle | ✅ |-| Java 22+ (`java App.java`) | the same C bridge, through the FFM API | ✅ |+| Java 22+ (`java App.java`, Maven, Gradle) | the same C bridge, through the FFM API | ✅ || Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo) | ✅ || PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ || C, C++ | the same C bridge | next |diff --git a/examples/fuzzy-dedupe-cpp/fuzzy.cpp b/examples/fuzzy-dedupe-cpp/fuzzy.cppnew file mode 100644index 0000000..3227263--- /dev/null+++ b/examples/fuzzy-dedupe-cpp/fuzzy.cpp@@ -0,0 +1,52 @@+// Fuzzy string matching helpers.+#include <algorithm>+#include <cctype>+#include <string>+#include <utility>+#include <vector>++// Edit distance (by byte): how many inserts, deletes or substitutions turn a into b.+static int levenshtein(const std::string &a, const std::string &b) {+ const std::string &s = a.size() >= b.size() ? a : b;+ const std::string &t = a.size() >= b.size() ? b : a;+ std::vector<int> previous(t.size() + 1), current(t.size() + 1);+ for (size_t j = 0; j <= t.size(); j++) previous[j] = (int) j;+ for (size_t i = 1; i <= s.size(); i++) {+ current[0] = (int) i;+ for (size_t j = 1; j <= t.size(); j++) {+ int cost = s[i - 1] == t[j - 1] ? 0 : 1;+ current[j] = std::min({previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost});+ }+ std::swap(previous, current);+ }+ return previous[t.size()];+}++// Lowercase (ASCII) and squeeze whitespace.+static std::string normalize(const std::string &name) {+ std::string out;+ bool space = false;+ for (unsigned char c : name) {+ if (std::isspace(c)) {+ space = !out.empty();+ continue;+ }+ if (space) out += ' ';+ space = false;+ out += (char) std::tolower(c);+ }+ return out;+}++// Index pairs of names within max_distance edits of each other.+std::vector<std::pair<int, int>> find_duplicates(const std::vector<std::string> &names, int max_distance) {+ std::vector<std::string> clean;+ for (const auto &n : names) clean.push_back(normalize(n));+ std::vector<std::pair<int, int>> pairs;+ for (size_t i = 0; i < clean.size(); i++) {+ for (size_t j = i + 1; j < clean.size(); j++) {+ if (levenshtein(clean[i], clean[j]) <= max_distance) pairs.emplace_back((int) i, (int) j);+ }+ }+ return pairs;+}diff --git a/examples/fuzzy-dedupe-cpp/main.cpp b/examples/fuzzy-dedupe-cpp/main.cppnew file mode 100644index 0000000..bf174c9--- /dev/null+++ b/examples/fuzzy-dedupe-cpp/main.cpp@@ -0,0 +1,30 @@+// Find near-duplicate customer names, the slow way.+// clang++ -O2 -std=c++17 main.cpp fuzzy.cpp -o dedupe+#include <cstdio>+#include <string>+#include <utility>+#include <vector>++std::vector<std::pair<int, int>> find_duplicates(const std::vector<std::string> &names, int max_distance);++static const char *FIRST[] = {"Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"};+static const char *LAST[] = {"Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka", "Wang",+ "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"};++int main() {+ unsigned long long seed = 7;+ auto next = [&](unsigned n) {+ seed = seed * 6364136223846793005ULL + 1442695040888963407ULL;+ return (unsigned) ((seed >> 33) % n);+ };+ std::vector<std::string> names;+ for (int k = 0; k < 6000; k++) {+ std::string name = std::string(FIRST[next(20)]) + " " + LAST[next(20)];+ if (next(100) < 35) name[next((unsigned) name.size())] = "aeiourstln"[next(10)];+ names.push_back(name);+ }+ auto pairs = find_duplicates(names, 2);+ std::printf("%zu names, %zu likely duplicate pairs\n", names.size(), pairs.size());+ return 0;+}diff --git a/examples/fuzzy-dedupe-cpp/reference/port.rs b/examples/fuzzy-dedupe-cpp/reference/port.rsnew file mode 100644index 0000000..6c0193c--- /dev/null+++ b/examples/fuzzy-dedupe-cpp/reference/port.rs@@ -0,0 +1,78 @@+//! Reference port of find_duplicates (with levenshtein and normalize inside it):+//! what a good agent run produces. CI uses it to test the pipeline without an agent.++/// The C++ normalize: ASCII lowercase, whitespace (std::isspace in the C locale) squeezed and trimmed, as bytes.+fn normalize(name: &str) -> Vec<u8> {+ let mut out = Vec::with_capacity(name.len());+ let mut space = false;+ for &c in name.as_bytes() {+ if matches!(c, b' ' | b'\t' | b'\n' | b'\x0B' | b'\x0C' | b'\r') {+ space = !out.is_empty();+ continue;+ }+ if space {+ out.push(b' ');+ }+ space = false;+ out.push(c.to_ascii_lowercase());+ }+ out+}++pub fn find_duplicates(names: Vec<String>, max_distance: i32) -> Result<Vec<(i32, i32)>, String> {+ if max_distance < 0 {+ return Ok(Vec::new());+ }+ let clean: Vec<Vec<u8>> = names.iter().map(|n| normalize(n)).collect();+ Ok(pairs(&clean, max_distance 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/examples/fuzzy-dedupe-java-build/.gitignore b/examples/fuzzy-dedupe-java-build/.gitignorenew file mode 100644index 0000000..37688ed--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/.gitignore@@ -0,0 +1,3 @@+target/+build/+.gradle/diff --git a/examples/fuzzy-dedupe-java-build/build.gradle.kts b/examples/fuzzy-dedupe-java-build/build.gradle.ktsnew file mode 100644index 0000000..ea7ae21--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/build.gradle.kts@@ -0,0 +1,13 @@+// The Java fuzzy-dedupe demo as a Gradle build: gradle -q run+plugins {+ application+}++application {+ mainClass = "demo.App"+}++tasks.withType<JavaCompile> {+ options.release = 25+ options.encoding = "UTF-8"+}diff --git a/examples/fuzzy-dedupe-java-build/pom.xml b/examples/fuzzy-dedupe-java-build/pom.xmlnew file mode 100644index 0000000..a3e5f4a--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/pom.xml@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="UTF-8"?>+<!-- The Java fuzzy-dedupe demo as a Maven build: mvn -q compile exec:java -->+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">+ <modelVersion>4.0.0</modelVersion>+ <groupId>demo</groupId>+ <artifactId>fuzzy-dedupe</artifactId>+ <version>1.0</version>++ <properties>+ <maven.compiler.release>25</maven.compiler.release>+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>+ </properties>++ <build>+ <plugins>+ <plugin>+ <groupId>org.codehaus.mojo</groupId>+ <artifactId>exec-maven-plugin</artifactId>+ <version>3.6.2</version>+ <configuration>+ <mainClass>demo.App</mainClass>+ </configuration>+ </plugin>+ </plugins>+ </build>+</project>diff --git a/examples/fuzzy-dedupe-java-build/reference/port.rs b/examples/fuzzy-dedupe-java-build/reference/port.rsnew file mode 100644index 0000000..0656fcd--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/reference/port.rs@@ -0,0 +1,75 @@+//! Reference port of Fuzzy.findDuplicates (with levenshtein and normalize inside it):+//! what a good agent run produces. CI uses it to test the pipeline without an agent.+#![allow(non_snake_case)]++/// Java's String.join(" ", s.toLowerCase(Locale.ROOT).trim().split("\\s+")), as UTF-16 units.+fn normalize(name: &str) -> Vec<u16> {+ let lower = name.to_lowercase();+ let trimmed = lower.trim_matches(|c: char| c <= ' ');+ let mut out = Vec::with_capacity(trimmed.len());+ for word in trimmed.split(|c: char| matches!(c, ' ' | '\t' | '\n' | '\x0B' | '\x0C' | '\r')).filter(|w| !w.is_empty()) {+ if !out.is_empty() {+ out.push(u16::from(b' '));+ }+ out.extend(word.encode_utf16());+ }+ out+}++pub fn findDuplicates(names: Vec<String>, maxDistance: i32) -> Result<Vec<[i32; 2]>, String> {+ if maxDistance < 0 {+ return Ok(Vec::new());+ }+ let clean: Vec<Vec<u16>> = names.iter().map(|n| normalize(n)).collect();+ Ok(pairs(&clean, maxDistance as usize).into_iter().map(|(i, j)| [i as i32, j as i32]).collect())+}++/// Edit distance, one row on the shorter side, common prefix and suffix skipped.+fn distance<T: PartialEq>(a: &[T], b: &[T], row: &mut Vec<usize>) -> usize {+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();+ let (a, b) = (&a[prefix..], &b[prefix..]);+ let suffix = a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count();+ let (a, b) = (&a[..a.len() - suffix], &b[..b.len() - suffix]);+ let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };+ if short.is_empty() {+ return long.len();+ }+ row.clear();+ row.extend(0..=short.len());+ for (i, ca) in long.iter().enumerate() {+ let mut diagonal = row[0];+ row[0] = i + 1;+ for (j, cb) in short.iter().enumerate() {+ let above = row[j + 1];+ row[j + 1] = (above + 1).min(row[j] + 1).min(diagonal + usize::from(ca != cb));+ diagonal = above;+ }+ }+ row[short.len()]+}++/// All (i, j) with i < j and distance <= max, in the original loop order, spread over threads.+fn pairs<T: PartialEq + Sync>(clean: &[Vec<T>], max: usize) -> Vec<(usize, usize)> {+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(clean.len().max(1));+ let mut found: Vec<(usize, usize)> = std::thread::scope(|s| {+ let workers: Vec<_> = (0..threads)+ .map(|t| {+ s.spawn(move || {+ let mut row = Vec::new();+ let mut out = Vec::new();+ for i in (t..clean.len()).step_by(threads) {+ for j in i + 1..clean.len() {+ if clean[i].len().abs_diff(clean[j].len()) <= max && distance(&clean[i], &clean[j], &mut row) <= max {+ out.push((i, j));+ }+ }+ }+ out+ })+ })+ .collect();+ workers.into_iter().flat_map(|w| w.join().expect("worker panicked")).collect()+ });+ found.sort_unstable();+ found+}diff --git a/examples/fuzzy-dedupe-java-build/settings.gradle.kts b/examples/fuzzy-dedupe-java-build/settings.gradle.ktsnew file mode 100644index 0000000..f1564d6--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/settings.gradle.kts@@ -0,0 +1 @@+rootProject.name = "fuzzy-dedupe"diff --git a/examples/fuzzy-dedupe-java-build/src/main/java/demo/App.java b/examples/fuzzy-dedupe-java-build/src/main/java/demo/App.javanew file mode 100644index 0000000..6a9bb82--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/src/main/java/demo/App.java@@ -0,0 +1,40 @@+package demo;++// Find near-duplicate customer names, the slow way.+// mvn -q compile exec:java or gradle -q run+import java.util.Random;++public class App {+ static final String[] FIRST = {"Maria", "Giulia", "Sofia", "Luca", "Marco", "Matteo", "José", "Zoë", "Łukasz", "Aiko",+ "Chen", "Olga", "Ahmed", "Fatima", "Liam", "Emma", "Noah", "Ava", "Mateo", "Ingrid"};+ static final String[] LAST = {"Rossi", "Russo", "Ferrari", "Esposito", "Bianchi", "García", "Müller", "Nowak", "Tanaka",+ "Wang", "Ivanova", "Haddad", "Smith", "Johnson", "Brown", "Silva", "Kowalski", "Novák", "Dubois", "Larsen"};++ static String[] makeNames(int count, long seed) {+ Random rng = new Random(seed);+ String[] names = new String[count];+ for (int k = 0; k < count; k++) {+ String name = FIRST[rng.nextInt(FIRST.length)] + " " + LAST[rng.nextInt(LAST.length)];+ if (rng.nextDouble() < 0.35) {+ int i = rng.nextInt(name.length());+ name = name.substring(0, i) + "aeiourstln".charAt(rng.nextInt(10)) + name.substring(i + 1);+ }+ names[k] = name;+ }+ return names;+ }++ public static void main(String[] args) {+ String[] names = makeNames(4000, 7);+ int[][] pairs = Fuzzy.findDuplicates(names, 2);+ System.out.println(names.length + " names, " + pairs.length + " likely duplicate pairs");+ int shown = 0;+ for (int[] p : pairs) {+ if (shown == 5) break;+ if (!names[p[0]].equals(names[p[1]])) {+ System.out.println(" " + names[p[0]] + " ~ " + names[p[1]]);+ shown++;+ }+ }+ }+}diff --git a/examples/fuzzy-dedupe-java-build/src/main/java/demo/Fuzzy.java b/examples/fuzzy-dedupe-java-build/src/main/java/demo/Fuzzy.javanew file mode 100644index 0000000..7085f24--- /dev/null+++ b/examples/fuzzy-dedupe-java-build/src/main/java/demo/Fuzzy.java@@ -0,0 +1,46 @@+package demo;++// Fuzzy string matching helpers.+import java.util.ArrayList;+import java.util.List;+import java.util.Locale;++class Fuzzy {+ // Edit distance: how many inserts, deletes or substitutions turn a into b.+ static int levenshtein(String a, String b) {+ if (a.length() < b.length()) {+ String t = a;+ a = b;+ b = t;+ }+ int[] previous = new int[b.length() + 1];+ for (int j = 0; j <= b.length(); j++) previous[j] = j;+ for (int i = 1; i <= a.length(); i++) {+ int[] current = new int[b.length() + 1];+ current[0] = i;+ for (int j = 1; j <= b.length(); j++) {+ int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;+ current[j] = Math.min(Math.min(previous[j] + 1, current[j - 1] + 1), previous[j - 1] + cost);+ }+ previous = current;+ }+ return previous[b.length()];+ }++ static String normalize(String name) {+ return String.join(" ", name.toLowerCase(Locale.ROOT).trim().split("\\s+"));+ }++ // Index pairs of names within maxDistance edits of each other.+ static int[][] findDuplicates(String[] names, int maxDistance) {+ String[] clean = new String[names.length];+ for (int i = 0; i < names.length; i++) clean[i] = normalize(names[i]);+ List<int[]> pairs = new ArrayList<>();+ for (int i = 0; i < clean.length; i++) {+ for (int j = i + 1; j < clean.length; j++) {+ if (levenshtein(clean[i], clean[j]) <= maxDistance) pairs.add(new int[]{i, j});+ }+ }+ return pairs.toArray(new int[0][]);+ }+}diff --git a/examples/mandelbrot-c/main.c b/examples/mandelbrot-c/main.cnew file mode 100644index 0000000..76ba9df--- /dev/null+++ b/examples/mandelbrot-c/main.c@@ -0,0 +1,16 @@+// Count the points inside the Mandelbrot set at a few zoom levels, the slow way.+// clang -O2 main.c mandelbrot.c -o mandelbrot+#include <stdio.h>++long long mandelbrot(int width, int height, int max_iter);++int main(void) {+ long long total = 0;+ for (int k = 1; k <= 8; k++) {+ long long inside = mandelbrot(160 * k, 120 * k, 2000);+ printf("%4dx%-4d %lld points inside\n", 160 * k, 120 * k, inside);+ total += inside;+ }+ printf("total %lld\n", total);+ return 0;+}diff --git a/examples/mandelbrot-c/mandelbrot.c b/examples/mandelbrot-c/mandelbrot.cnew file mode 100644index 0000000..e72a1e7--- /dev/null+++ b/examples/mandelbrot-c/mandelbrot.c@@ -0,0 +1,20 @@+// How many points of a width x height grid over [-2, 1] x [-1.5, 1.5] stay bounded for max_iter steps.+long long mandelbrot(int width, int height, int max_iter) {+ long long inside = 0;+ for (int py = 0; py < height; py++) {+ for (int px = 0; px < width; px++) {+ double x0 = -2.0 + 3.0 * px / width;+ double y0 = -1.5 + 3.0 * py / height;+ double x = 0.0, y = 0.0;+ int i = 0;+ while (x * x + y * y <= 4.0 && i < max_iter) {+ double t = x * x - y * y + x0;+ y = 2.0 * x * y + y0;+ x = t;+ i++;+ }+ if (i == max_iter) inside++;+ }+ }+ return inside;+}diff --git a/examples/mandelbrot-c/reference/port.rs b/examples/mandelbrot-c/reference/port.rsnew file mode 100644index 0000000..e319a8f--- /dev/null+++ b/examples/mandelbrot-c/reference/port.rs@@ -0,0 +1,37 @@+//! Reference port of mandelbrot: what a good agent run produces. CI uses it to test the pipeline+//! without an agent. Same arithmetic in the same order (so the same doubles), rows spread over threads.++pub fn mandelbrot(width: i32, height: i32, max_iter: i32) -> Result<i64, String> {+ if width <= 0 || height <= 0 {+ return Ok(0);+ }+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(height as usize);+ let total = std::thread::scope(|s| {+ let workers: Vec<_> = (0..threads)+ .map(|t| {+ s.spawn(move || {+ let mut inside = 0i64;+ for py in (t as i32..height).step_by(threads) {+ let y0 = -1.5 + 3.0 * py as f64 / height as f64;+ for px in 0..width {+ let x0 = -2.0 + 3.0 * px as f64 / width as f64;+ let (mut x, mut y, mut i) = (0.0f64, 0.0f64, 0);+ while x * x + y * y <= 4.0 && i < max_iter {+ let t = x * x - y * y + x0;+ y = 2.0 * x * y + y0;+ x = t;+ i += 1;+ }+ if i == max_iter {+ inside += 1;+ }+ }+ }+ inside+ })+ })+ .collect();+ workers.into_iter().map(|w| w.join().expect("worker panicked")).sum::<i64>()+ });+ Ok(total)+}diff --git a/src/backend.rs b/src/backend.rsindex 873c41a..5b85d00 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::{golang, java, node, php, python, ruby};+use crate::{cfamily, golang, java, node, php, python, ruby};use anyhow::{Context, Result, bail, ensure};use serde::{Deserialize, Serialize};use std::fs;@@ -21,6 +21,8 @@ pub enum Lang {Java,Go,Php,+ C,+ Cpp,}#[derive(Deserialize)]@@ -52,16 +54,18 @@ impl Lang {Ok(Lang::Go)} else if php::is_php(program) {Ok(Lang::Php)+ } else if let Some(lang) = cfamily::detect(program) {+ Ok(lang)} else {bail!(- "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java, Go and PHP. 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"+ "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++)")}}/// 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)+ matches!(self, Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp)}pub fn label(self) -> &'static str {@@ -72,6 +76,8 @@ impl Lang {Lang::Java => "Java",Lang::Go => "Go",Lang::Php => "PHP",+ Lang::C => "C",+ Lang::Cpp => "C++",}}@@ -83,6 +89,7 @@ impl Lang {Lang::Java => java::resolve(program, root),Lang::Go => golang::resolve(program, root),Lang::Php => php::resolve(program, root),+ Lang::C | Lang::Cpp => cfamily::resolve(program, root),}}@@ -94,6 +101,7 @@ impl Lang {Lang::Java => java::profile(ctx, exe, args),Lang::Go => golang::profile(ctx, exe, args),Lang::Php => php::profile(ctx, exe, args),+ Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),}}@@ -113,6 +121,7 @@ impl Lang {Lang::Java => java::record(ctx, exe, args, hs, out, limit),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),}}@@ -124,6 +133,7 @@ impl Lang {Lang::Java => java::scaffold(ctx, hs, helpers, port),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),}}@@ -135,6 +145,7 @@ impl Lang {Lang::Java => java::verify(ctx, port),Lang::Go => golang::verify(ctx, port),Lang::Php => php::verify(ctx, port),+ Lang::C | Lang::Cpp => cfamily::verify(ctx, port),}}@@ -146,6 +157,7 @@ impl Lang {Lang::Java => java::enable(ctx, port),Lang::Go => golang::enable(ctx, port),Lang::Php => php::enable(ctx, port),+ Lang::C | Lang::Cpp => cfamily::enable(ctx, port),}}@@ -157,6 +169,7 @@ impl Lang {Lang::Java => java::disable(ctx, port),Lang::Go => golang::disable(ctx, port),Lang::Php => php::disable(ctx, port),+ Lang::C | Lang::Cpp => cfamily::disable(ctx, port),}}@@ -165,6 +178,8 @@ impl Lang {let exe = ctx.runtime()?;match self {Lang::Go => golang::bench_command(ctx, exe),+ Lang::Java => java::bench_command(ctx, exe),+ Lang::C | Lang::Cpp => cfamily::bench_command(ctx, exe),_ => Ok((exe.to_string(), ctx.state.command[1..].to_vec())),}}@@ -183,7 +198,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 => built.clone(),+ Lang::Ruby | Lang::Java | Lang::Go | Lang::Php | Lang::C | Lang::Cpp => built.clone(),};(built, dest)}diff --git a/src/cfamily.rs b/src/cfamily.rsnew file mode 100644index 0000000..113dace--- /dev/null+++ b/src/cfamily.rs@@ -0,0 +1,1403 @@+//! C and C++ backend: apps built with gcc or clang, e.g. clang -O2 main.c fuzzy.c (app arguments+//! after a second --). fast-anything builds the binary itself into .fast/bin. Profiled with a+//! one-line timer per function for one run, read with a small declaration parser, and bridged with+//! a block appended to the source file that loads the port with LoadLibrary or dlopen.++use crate::backend::{self, Lang, 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, ensure};+use serde_json::Value;+use std::collections::BTreeMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++const PROF_H: &str = include_str!("cfamily/prof.h");+const PROF_C: &str = include_str!("cfamily/prof.c");+const CLOCK_H: &str = include_str!("cfamily/clock.h");+const REC_H: &str = include_str!("cfamily/rec.h");+const REC_C: &str = include_str!("cfamily/rec.c");+const REC_HPP: &str = include_str!("cfamily/rec.hpp");+const JSON_HPP: &str = include_str!("cfamily/json.hpp");++const C_COMPILERS: &[&str] = &["gcc", "clang", "cc"];+const CPP_COMPILERS: &[&str] = &["g++", "clang++", "c++"];+const C_EXT: &[&str] = &["c"];+const CPP_EXT: &[&str] = &["cc", "cpp", "cxx", "c++", "C"];+/// Compiler flags whose value is the next argument.+const VALUE_FLAGS: &[&str] =+ &["-o", "-I", "-D", "-U", "-include", "-isystem", "-L", "-l", "-x", "-MF", "-MT", "-target"];++fn base_name(program: &str) -> String {+ // gcc-14, clang-19, x86_64-linux-gnu-g++ ...+ let stem = util::program_stem(program);+ stem.rsplit('-').find(|p| !p.chars().all(|c| c.is_ascii_digit() || c == '.')).unwrap_or(&stem).to_string()+}++pub fn detect(program: &str) -> Option<Lang> {+ let b = base_name(program);+ if CPP_COMPILERS.contains(&b.as_str()) {+ Some(Lang::Cpp)+ } else if C_COMPILERS.contains(&b.as_str()) {+ Some(Lang::C)+ } else {+ None+ }+}++/// A C compiler given C++ sources still builds C++.+pub fn refine(lang: Lang, args: &[String]) -> Lang {+ if lang == Lang::C && Build::parse(args).is_ok_and(|b| b.sources.iter().any(|s| is_cpp_file(s))) {+ Lang::Cpp+ } else {+ lang+ }+}++fn is_cpp_file(path: &str) -> bool {+ Path::new(path).extension().is_some_and(|e| CPP_EXT.contains(&e.to_string_lossy().as_ref()))+}++pub fn resolve(program: &str, root: &Path) -> Result<String> {+ let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };+ let out = output(Command::new(&prog).arg("--version").current_dir(root), program)?;+ ensure!(out.status.success(), "{program} failed:\n{}", tail(&combined(&out), 5));+ Ok(prog.to_string_lossy().into_owned())+}++/// compiler [flags] sources... [-o out] [-- app args]+struct Build {+ flags: Vec<String>,+ sources: Vec<String>,+ args: Vec<String>,+}++impl Build {+ fn parse(args: &[String]) -> Result<Build> {+ let (compile, app) = match args.iter().position(|a| a == "--") {+ Some(i) => (&args[..i], args[i + 1..].to_vec()),+ None => (args, Vec::new()),+ };+ let (mut flags, mut sources) = (Vec::new(), Vec::new());+ let mut i = 0;+ while i < compile.len() {+ let a = &compile[i];+ if a == "-o" {+ i += 2;+ continue;+ }+ let ext = Path::new(a).extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();+ if !a.starts_with('-') && (C_EXT.contains(&ext.as_str()) || CPP_EXT.contains(&ext.as_str())) {+ sources.push(a.clone());+ } else {+ flags.push(a.clone());+ if VALUE_FLAGS.contains(&a.as_str()) && i + 1 < compile.len() {+ flags.push(compile[i + 1].clone());+ i += 1;+ }+ }+ i += 1;+ }+ ensure!(+ !sources.is_empty(),+ "give the sources to compile: fast-anything scan -- clang -O2 main.c fuzzy.c (app arguments after a second --)"+ );+ Ok(Build { flags, sources, args: app })+ }+}++fn binary(ctx: &Ctx) -> PathBuf {+ ctx.fast.join("bin").join(if cfg!(windows) { "app.exe" } else { "app" })+}++/// Copies the runtime files into .fast/cfa and returns that folder.+fn runtime_dir(ctx: &Ctx) -> Result<PathBuf> {+ let dir = ctx.fast.join("cfa");+ fs::create_dir_all(&dir)?;+ for (name, text) in [+ ("fa_prof.h", PROF_H.to_string()),+ ("fa_clock.h", CLOCK_H.to_string()),+ ("fa_rec.h", REC_H.to_string()),+ ("fa_rec.hpp", REC_HPP.replace("/*JSON*/", JSON_HPP)),+ ] {+ fs::write(dir.join(name), text)?;+ }+ Ok(dir)+}++fn compile(ctx: &Ctx, cc: &str, b: &Build, extra: &[PathBuf], include: Option<&Path>) -> Result<PathBuf> {+ let bin = binary(ctx);+ fs::create_dir_all(bin.parent().context("bin")?)?;+ let mut cmd = Command::new(cc);+ cmd.args(&b.flags).args(&b.sources).args(extra).current_dir(&ctx.root).arg("-o").arg(&bin);+ if let Some(h) = include {+ cmd.arg("-include").arg(h);+ }+ let out = output(&mut cmd, cc)?;+ ensure!(out.status.success(), "building the app failed:\n{}", tail(&combined(&out), 30));+ Ok(bin)+}++fn run(ctx: &Ctx, bin: &Path, b: &Build, env: &[(&str, &Path)], derive: bool) -> Result<std::process::Output> {+ let mut cmd = Command::new(bin);+ cmd.args(&b.args).current_dir(&ctx.root).env(DISABLE_ENV, "1").stdin(Stdio::null());+ for (k, v) in env {+ cmd.env(k, v);+ }+ if !derive {+ cmd.env("FAST_ANYTHING_RECORD_DERIVE", "0");+ }+ output(&mut cmd, "the app")+}++pub fn bench_command(ctx: &Ctx, cc: &str) -> Result<(String, Vec<String>)> {+ let b = Build::parse(&ctx.state.command[1..])?;+ let bin = compile(ctx, cc, &b, &[], None)?;+ Ok((bin.to_string_lossy().into_owned(), b.args))+}++// ------------------------------------------------------------------ reading the source++/// The source with comments, string and character literals and preprocessor lines blanked out+/// (same length, newlines kept), so braces and parentheses can be counted.+fn blank(src: &str) -> String {+ let b = src.as_bytes();+ let mut out = b.to_vec();+ let mut i = 0;+ let mut line_start = true;+ let wipe = |out: &mut Vec<u8>, from: usize, to: usize| {+ for c in &mut out[from..to] {+ if *c != b'\n' {+ *c = b' ';+ }+ }+ };+ while i < b.len() {+ let c = b[i];+ if line_start && c == b'#' {+ let start = i;+ while i < b.len() && !(b[i] == b'\n' && b[i - 1] != b'\\') {+ i += 1;+ }+ wipe(&mut out, start, i);+ continue;+ }+ if c == b'\n' {+ line_start = true;+ i += 1;+ continue;+ }+ if !c.is_ascii_whitespace() {+ line_start = false;+ }+ if c == b'/' && b.get(i + 1) == Some(&b'/') {+ let start = i;+ while i < b.len() && b[i] != b'\n' {+ i += 1;+ }+ wipe(&mut out, start, i);+ } else if c == b'/' && b.get(i + 1) == Some(&b'*') {+ let start = i;+ i += 2;+ while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {+ i += 1;+ }+ i = (i + 2).min(b.len());+ wipe(&mut out, start, i);+ } else if c == b'"' || c == b'\'' {+ let start = i;+ i += 1;+ while i < b.len() && b[i] != c && b[i] != b'\n' {+ i += if b[i] == b'\\' { 2 } else { 1 };+ }+ i = (i + 1).min(b.len());+ wipe(&mut out, start + 1, i.saturating_sub(1).max(start + 1));+ } else {+ i += 1;+ }+ }+ String::from_utf8(out).unwrap_or_default()+}++fn words(s: &str) -> impl Iterator<Item = &str> {+ s.split(|c: char| !(c.is_alphanumeric() || c == '_')).filter(|w| !w.is_empty())+}++const SPECIFIERS: &[&str] = &[+ "static",+ "inline",+ "extern",+ "constexpr",+ "consteval",+ "virtual",+ "explicit",+ "friend",+ "__inline",+ "__forceinline",+ "register",+];+const KEYWORDS: &[&str] = &[+ "if",+ "for",+ "while",+ "switch",+ "catch",+ "return",+ "sizeof",+ "else",+ "do",+ "case",+ "new",+ "delete",+ "throw",+ "alignof",+ "decltype",+ "static_assert",+ "defined",+];+const IO: &[&str] = &[+ "printf", "fprintf", "puts", "fputs", "putchar", "fputc", "fwrite", "fread", "fopen", "fclose", "fgets", "fgetc",+ "getchar", "scanf", "fscanf", "perror", "system", "exit", "abort", "getline", "cout", "cerr", "cin", "clog",+ "ofstream", "ifstream", "fstream", "sleep", "usleep", "Sleep", "remove", "rename", "getenv", "open", "read",+ "write", "close", "send", "recv", "socket", "thread", "async",+];+const NONDET: &[&str] = &[+ "rand",+ "srand",+ "random",+ "time",+ "clock",+ "random_device",+ "system_clock",+ "steady_clock",+ "high_resolution_clock",+ "mt19937",+ "default_random_engine",+];++#[derive(Debug, Clone)]+struct CFunc {+ name: String,+ namespaces: Vec<String>,+ class: Option<String>,+ is_static: bool,+ template: bool,+ body_open: usize,+ body_close: usize,+ params: Vec<Param>,+ ret: String,+}++#[derive(Debug)]+enum Scope {+ Namespace(String),+ Transparent,+ Class(String),+ Body(usize),+ Other,+}++fn match_back(s: &[u8], close: usize, open: u8, shut: u8) -> Option<usize> {+ let mut depth = 0i32;+ let mut i = close as isize;+ while i >= 0 {+ let c = s[i as usize];+ if c == shut {+ depth += 1;+ } else if c == open {+ depth -= 1;+ if depth == 0 {+ return Some(i as usize);+ }+ }+ i -= 1;+ }+ None+}++fn split_top(s: &str, sep: u8) -> Vec<&str> {+ let b = s.as_bytes();+ let (mut depth, mut start, mut out) = (0i32, 0, Vec::new());+ for (i, &c) in b.iter().enumerate() {+ match c {+ b'(' | b'<' | b'[' | b'{' => depth += 1,+ b')' | b'>' | b']' | b'}' => depth -= 1,+ _ if c == sep && depth == 0 => {+ out.push(&s[start..i]);+ start = i + 1;+ }+ _ => {}+ }+ }+ out.push(&s[start..]);+ out+}++fn squash(s: &str) -> String {+ s.split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+ .replace(" *", "*")+ .replace("* ", "*")+ .replace(" &", "&")+ .replace("& ", "&")+ .replace("< ", "<")+ .replace(" >", ">")+ .replace(", ", ",")+}++fn parse_params(list: &str) -> Vec<Param> {+ let list = list.trim();+ if list.is_empty() || list == "void" {+ return vec![];+ }+ split_top(list, b',')+ .into_iter()+ .map(|p| {+ let mut parts = split_top(p, b'=').into_iter();+ let decl = parts.next().unwrap_or_default().trim();+ let default = parts.next().map(|d| d.trim().to_string());+ let (decl, array) = match decl.strip_suffix(']').and_then(|d| d.rfind('[').map(|i| &d[..i])) {+ Some(d) => (d.trim_end(), true),+ None => (decl, false),+ };+ let name_start = decl.rfind(|c: char| !(c.is_alphanumeric() || c == '_')).map(|i| i + 1).unwrap_or(0);+ let (ty, name) = (decl[..name_start].trim(), &decl[name_start..]);+ let (ty, name) = if ty.is_empty() || ty.ends_with("::") { (decl, "") } else { (ty, name) };+ let ty = if array { format!("{}*", ty.trim()) } else { ty.to_string() };+ Param { name: name.to_string(), annotation: Some(squash(&ty)), default }+ })+ .collect()+}++fn parse(src: &str) -> Vec<CFunc> {+ let text = blank(src);+ let b = text.as_bytes();+ let mut stack: Vec<Scope> = Vec::new();+ let mut stmt = 0usize;+ let mut found: Vec<CFunc> = Vec::new();+ let decl_scope = |stack: &Vec<Scope>| {+ stack.iter().all(|s| matches!(s, Scope::Namespace(_) | Scope::Transparent | Scope::Class(_)))+ };+ for i in 0..b.len() {+ match b[i] {+ b'{' => {+ if !decl_scope(&stack) {+ stack.push(Scope::Other);+ continue;+ }+ let head = text[stmt..i].trim();+ let w: Vec<&str> = words(head).collect();+ let scope = if w.first() == Some(&"namespace") {+ Scope::Namespace(w.get(1).map(|s| s.to_string()).unwrap_or_default())+ } else if w == ["extern"] {+ Scope::Transparent+ } else if let Some(k) = w+ .iter()+ .position(|x| ["class", "struct", "union"].contains(x))+ .filter(|_| !head.contains('(') && !head.contains('='))+ {+ if w.get(k).is_some_and(|x| *x == "union") {+ Scope::Other+ } else {+ Scope::Class(w.get(k + 1).map(|s| s.to_string()).unwrap_or_default())+ }+ } else if let Some(f) = function_head(head, i, &stack) {+ found.push(f);+ Scope::Body(found.len() - 1)+ } else {+ Scope::Other+ };+ stack.push(scope);+ stmt = i + 1;+ }+ b'}' => {+ if let Some(Scope::Body(k)) = stack.pop() {+ found[k].body_close = i;+ }+ if decl_scope(&stack) {+ stmt = i + 1;+ }+ }+ b';' if decl_scope(&stack) => stmt = i + 1,+ b':' if decl_scope(&stack) && b.get(i + 1) != Some(&b':') && i > 0 && b[i - 1] != b':' => {+ let head = text[stmt..i].trim();+ if ["public", "private", "protected"].contains(&head) {+ stmt = i + 1;+ }+ }+ _ => {}+ }+ }+ found.retain(|f| f.body_close > f.body_open);+ found+}++fn function_head(head: &str, brace: usize, stack: &[Scope]) -> Option<CFunc> {+ let hb = head.as_bytes();+ let close = head.rfind(')')?;+ let after = &head[close + 1..];+ if !words(after).all(|w| ["const", "noexcept", "override", "final", "mutable"].contains(&w))+ || after.contains("->")+ || after.contains(':')+ {+ return None;+ }+ let open = match_back(hb, close, b'(', b')')?;+ let before = head[..open].trim_end();+ let name_start =+ before.rfind(|c: char| !(c.is_alphanumeric() || c == '_' || c == ':' || c == '~')).map(|i| i + 1).unwrap_or(0);+ let name = &before[name_start..];+ let prefix = before[..name_start].trim();+ if name.is_empty()+ || prefix.is_empty()+ || KEYWORDS.contains(&name)+ || name.contains("operator")+ || name.contains('~')+ {+ return None;+ }+ let template = prefix.starts_with("template");+ let is_static = words(prefix).any(|w| w == "static");+ let mut ret = prefix.to_string();+ if template && let Some(gt) = ret.find('>') {+ ret = ret[gt + 1..].to_string();+ }+ let ret = squash(&words_except(&ret, SPECIFIERS));+ let namespaces =+ stack.iter().filter_map(|s| if let Scope::Namespace(n) = s { Some(n.clone()) } else { None }).collect();+ let class = stack.iter().rev().find_map(|s| if let Scope::Class(n) = s { Some(n.clone()) } else { None });+ Some(CFunc {+ name: name.to_string(),+ namespaces,+ class,+ is_static,+ template,+ body_open: brace,+ body_close: 0,+ params: parse_params(&head[open + 1..close]),+ ret,+ })+}++/// Removes whole words (specifiers, attributes) from a declaration, keeping everything else.+fn words_except(s: &str, drop: &[&str]) -> String {+ let mut out = String::new();+ let mut word = String::new();+ let flush = |word: &mut String, out: &mut String| {+ if !drop.contains(&word.as_str()) {+ out.push_str(word);+ }+ word.clear();+ };+ for c in s.chars() {+ if c.is_alphanumeric() || c == '_' {+ word.push(c);+ } else {+ flush(&mut word, &mut out);+ out.push(c);+ }+ }+ flush(&mut word, &mut out);+ let out = out.trim().to_string();+ // [[nodiscard]] and __attribute__((...))+ let mut cleaned = out.clone();+ while let Some(a) = cleaned.find("[[") {+ let Some(z) = cleaned[a..].find("]]") else { break };+ cleaned.replace_range(a..a + z + 2, "");+ }+ while let Some(a) = cleaned.find("__attribute__") {+ let rest = &cleaned[a..];+ let Some(open) = rest.find('(') else { break };+ let Some(close) = match_forward(rest.as_bytes(), open) else { break };+ cleaned.replace_range(a..a + close + 1, "");+ }+ cleaned.trim().to_string()+}++fn match_forward(s: &[u8], open: usize) -> Option<usize> {+ let mut depth = 0;+ for (i, &c) in s.iter().enumerate().skip(open) {+ if c == b'(' {+ depth += 1;+ } else if c == b')' {+ depth -= 1;+ if depth == 0 {+ return Some(i);+ }+ }+ }+ None+}++// ------------------------------------------------------------------ types++#[derive(Debug, Clone, Copy, PartialEq)]+enum Scalar {+ Int { signed: bool, rust: &'static str },+ Float(&'static str),+ Bool,+}++fn scalar(t: &str) -> Option<Scalar> {+ let t = squash(t).replace("const ", "").replace("std::", "");+ let t = t.trim();+ let int = |signed, rust| Some(Scalar::Int { signed, rust });+ match t {+ "char" | "signed char" | "int8_t" => int(true, "i8"),+ "unsigned char" | "uint8_t" => int(false, "u8"),+ "short" | "short int" | "signed short" | "int16_t" => int(true, "i16"),+ "unsigned short" | "unsigned short int" | "uint16_t" => int(false, "u16"),+ "int" | "signed" | "signed int" | "int32_t" => int(true, "i32"),+ "unsigned" | "unsigned int" | "uint32_t" => int(false, "u32"),+ "long" | "long int" | "long long" | "long long int" | "int64_t" | "ssize_t" | "ptrdiff_t" | "intptr_t" => {+ int(true, "i64")+ }+ "unsigned long"+ | "unsigned long int"+ | "unsigned long long"+ | "unsigned long long int"+ | "uint64_t"+ | "size_t"+ | "uintptr_t" => int(false, "u64"),+ "float" => Some(Scalar::Float("f32")),+ "double" | "long double" => Some(Scalar::Float("f64")),+ "bool" | "_Bool" => Some(Scalar::Bool),+ _ => None,+ }+}++/// What a C parameter is to the recorder and the bridge.+#[derive(Debug, Clone, PartialEq)]+enum CKind {+ Scalar(Scalar),+ Str,+ /// const T* data whose length is the parameter at this index+ Array(Scalar, usize),+ Len,+}++fn c_kinds(params: &[Param]) -> std::result::Result<Vec<CKind>, String> {+ let mut kinds: Vec<Option<CKind>> = vec![None; params.len()];+ for (i, p) in params.iter().enumerate() {+ let t = squash(p.annotation.as_deref().unwrap_or(""));+ if kinds[i].is_some() {+ continue;+ }+ if let Some(s) = scalar(&t) {+ kinds[i] = Some(CKind::Scalar(s));+ } else if t == "const char*" || t == "char const*" {+ kinds[i] = Some(CKind::Str);+ } else if let Some(inner) = t.strip_suffix('*').filter(|_| t.starts_with("const ") || t.contains(" const*")) {+ let inner = inner.replace("const", "");+ let s = scalar(&inner).ok_or_else(|| format!("takes a {t}"))?;+ let len = params.get(i + 1).and_then(|n| scalar(n.annotation.as_deref().unwrap_or("")));+ ensure_len(len, &t)?;+ kinds[i] = Some(CKind::Array(s, i + 1));+ kinds[i + 1] = Some(CKind::Len);+ } else if t.ends_with('*') {+ return Err(format!("takes a pointer it may write through ({t})"));+ } else {+ return Err(format!("takes a {t}"));+ }+ }+ Ok(kinds.into_iter().map(|k| k.unwrap_or(CKind::Len)).collect())+}++fn ensure_len(len: Option<Scalar>, t: &str) -> std::result::Result<(), String> {+ match len {+ Some(Scalar::Int { .. }) => Ok(()),+ _ => Err(format!("takes a {t} without a length right after it")),+ }+}++/// C++ types fast-anything can carry across: scalars, std::string, vector, array, map/unordered_map+/// with string keys and pair, by value or const reference.+fn cpp_rust_type(t: &str) -> Option<String> {+ let t = squash(t);+ let t = t.trim().trim_start_matches("const ").trim_end_matches('&').trim();+ let t = t.strip_suffix(" const").unwrap_or(t).trim();+ if let Some(s) = scalar(t) {+ return Some(scalar_rust(s).into());+ }+ let t = t.strip_prefix("std::").unwrap_or(t);+ if t == "string" || t == "const char*" {+ return Some("String".into());+ }+ let (raw, inner) = t.strip_suffix('>')?.split_once('<')?;+ let args = split_top(inner, b',');+ Some(match (raw, args.as_slice()) {+ ("vector", [x, ..]) => format!("Vec<{}>", cpp_rust_type(x)?),+ ("array", [x, n]) => format!("[{}; {}]", cpp_rust_type(x)?, n.trim().parse::<usize>().ok()?),+ ("map", [k, v, ..]) if cpp_rust_type(k)? == "String" => {+ format!("std::collections::BTreeMap<String, {}>", cpp_rust_type(v)?)+ }+ ("unordered_map", [k, v, ..]) if cpp_rust_type(k)? == "String" => {+ format!("std::collections::HashMap<String, {}>", cpp_rust_type(v)?)+ }+ ("pair", [a, b]) => format!("({}, {})", cpp_rust_type(a)?, cpp_rust_type(b)?),+ _ => return None,+ })+}++fn scalar_rust(s: Scalar) -> &'static str {+ match s {+ Scalar::Int { rust, .. } | Scalar::Float(rust) => rust,+ Scalar::Bool => "bool",+ }+}++pub fn rust_type_c(t: &str) -> Option<String> {+ let t = squash(t);+ if let Some(s) = scalar(&t) {+ return Some(scalar_rust(s).into());+ }+ if t == "const char*" {+ return Some("String".into());+ }+ let inner = t.strip_suffix('*')?.replace("const", "");+ Some(format!("Vec<{}>", scalar_rust(scalar(&inner)?)))+}++fn blockers(f: &CFunc, body: &str, cpp: bool, funcs: &[CFunc]) -> (Vec<String>, Vec<String>, Vec<String>) {+ let mut blockers = Vec::new();+ let mut warnings = Vec::new();+ if f.class.is_some() && !f.is_static {+ blockers.push("instance method (static methods and free functions only for now)".into());+ }+ if f.name.contains("::") {+ blockers.push("method defined outside its class".into());+ }+ if f.template {+ blockers.push("template".into());+ }+ if f.name == "main" {+ blockers.push("the entry point".into());+ }+ if f.params.iter().any(|p| p.name.is_empty()) {+ blockers.push("has unnamed parameters".into());+ }+ if cpp {+ for p in &f.params {+ let t = p.annotation.clone().unwrap_or_default();+ if (t.ends_with('&') && !t.starts_with("const")) || t.ends_with("&&") {+ blockers.push(format!("takes a non-const reference ({t})"));+ } else if cpp_rust_type(&t).is_none() {+ blockers.push(format!("takes a {t}"));+ }+ }+ if f.ret == "void" {+ blockers.push("returns nothing (void)".into());+ } else if f.ret.ends_with('&') || f.ret.ends_with('*') || cpp_rust_type(&f.ret).is_none() {+ blockers.push(format!("returns a {}", f.ret));+ }+ } else {+ if let Err(e) = c_kinds(&f.params) {+ blockers.push(e);+ }+ if f.ret == "void" {+ blockers.push("returns nothing (void)".into());+ } else if scalar(&f.ret).is_none() {+ blockers.push(format!("returns a {} (C ports return numbers or bools for now)", f.ret));+ }+ }+ let b = body.as_bytes();+ let (mut io, mut nondet, mut helpers) = (Vec::new(), Vec::new(), Vec::new());+ let mut statics = false;+ let mut i = 0;+ while i < b.len() {+ if b[i].is_ascii_alphabetic() || b[i] == b'_' {+ let start = i;+ while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {+ i += 1;+ }+ let w = &body[start..i];+ let member = start >= 1 && (b[start - 1] == b'.' || (start >= 2 && &body[start - 2..start] == "->"));+ let mut j = i;+ while j < b.len() && b[j] == b' ' {+ j += 1;+ }+ let call = b.get(j) == Some(&b'(');+ if w == "static" {+ statics = true;+ }+ if !member+ && IO.contains(&w)+ && (call || ["cout", "cerr", "cin", "clog", "ofstream", "ifstream", "fstream", "thread"].contains(&w))+ {+ io.push(w.to_string());+ }+ if !member && NONDET.contains(&w) {+ nondet.push(w.to_string());+ }+ if !member && call && w != f.name && funcs.iter().any(|g| g.name == w && g.class == f.class) {+ helpers.push(w.to_string());+ }+ } else {+ i += 1;+ }+ }+ io.dedup();+ nondet.dedup();+ helpers.sort();+ helpers.dedup();+ if !io.is_empty() {+ blockers.push(format!("does I/O: {}", io.iter().take(3).cloned().collect::<Vec<_>>().join(", ")));+ }+ if !nondet.is_empty() {+ blockers.push(format!("not deterministic: {}", nondet.iter().take(3).cloned().collect::<Vec<_>>().join(", ")));+ }+ if statics {+ blockers.push("keeps static variables".into());+ }+ if !helpers.is_empty() {+ warnings.push(format!(+ "calls {}, they get ported together with it",+ helpers.iter().take(3).cloned().collect::<Vec<_>>().join(", ")+ ));+ }+ (blockers, warnings, helpers)+}++struct Described {+ path: PathBuf,+ f: CFunc,+ hs: Hotspot,+}++fn line_of(src: &str, offset: usize) -> u32 {+ src[..offset.min(src.len())].bytes().filter(|&c| c == b'\n').count() as u32 + 1+}++fn describe(ctx: &Ctx, b: &Build, lang: Lang) -> Result<Vec<Described>> {+ let mut out = Vec::new();+ for s in &b.sources {+ let path = util::absolute(&ctx.root.join(s));+ let src = fs::read_to_string(&path).with_context(|| format!("reading {s}"))?;+ let cpp = lang == Lang::Cpp || is_cpp_file(s);+ let funcs = parse(&src);+ let text = blank(&src);+ let file = util::forward_slashes(path.strip_prefix(&ctx.root).unwrap_or(&path));+ let module = file.rsplit_once('.').map(|(m, _)| m).unwrap_or(&file).replace('/', ".");+ for f in &funcs {+ let body = &text[f.body_open + 1..f.body_close];+ let (blockers, warnings, calls) = blockers(f, body, cpp, &funcs);+ // the declaration starts at the line of its return type+ let decl_start = src[..f.body_open]+ .rfind(&f.ret.split_whitespace().next().unwrap_or(&f.name).to_string())+ .unwrap_or(f.body_open);+ let line = line_of(&src, decl_start.min(f.body_open));+ let mut qual: Vec<String> = f.namespaces.iter().filter(|n| !n.is_empty()).cloned().collect();+ qual.extend(f.class.clone());+ qual.push(f.name.clone());+ let hs = Hotspot {+ file: file.clone(),+ line,+ end_line: line_of(&src, f.body_close),+ name: f.name.clone(),+ qualname: qual.join("."),+ module: Some(module.clone()),+ kind: "function".into(),+ portability: if blockers.is_empty() { 0.9 } else { 0.0 },+ blockers,+ warnings,+ params: f.params.clone(),+ returns: Some(f.ret.clone()),+ source: src[src[..f.body_open].rfind(['\n', ';', '}']).map(|i| i + 1).unwrap_or(0)..=f.body_close]+ .trim()+ .replace('\r', ""),+ calls,+ owner: f.class.clone(),+ ..Hotspot::default()+ };+ out.push(Described { path: path.clone(), f: f.clone(), hs });+ }+ }+ Ok(out)+}++fn insert_at(text: &str, mut at: Vec<(usize, String)>) -> String {+ at.sort_by_key(|a| std::cmp::Reverse(a.0));+ let mut out = text.to_string();+ for (offset, piece) in at {+ out.insert_str(offset, &piece);+ }+ out+}++/// The build with one runtime source added, written in the language the compiler builds.+fn runtime_source(dir: &Path, name: &str, text: &str, lang: Lang) -> Result<PathBuf> {+ let path = dir.join(format!("{name}.{}", if lang == Lang::Cpp { "cpp" } else { "c" }));+ fs::write(&path, text)?;+ Ok(path)+}++pub fn profile(ctx: &Ctx, cc: &str, args: &[String], lang: Lang) -> Result<Profile> {+ let b = Build::parse(args)?;+ let found = describe(ctx, &b, lang)?;+ let dir = runtime_dir(ctx)?;+ let prof_c = runtime_source(&dir, "fa_prof", PROF_C, lang)?;+ let mut by_file: BTreeMap<&Path, Vec<(usize, String)>> = BTreeMap::new();+ for (i, d) in found.iter().enumerate() {+ by_file.entry(&d.path).or_default().push((d.f.body_open + 1, format!(" FA_PROF({i});")));+ }+ let mut patches = Patches::new(ctx)?;+ for (path, at) in by_file {+ let text = fs::read_to_string(path)?;+ patches.write(path, &insert_at(&text, at))?;+ }+ let bin = compile(ctx, cc, &b, &[prof_c], Some(&dir.join("fa_prof.h")));+ patches.restore()?;+ let bin = bin?;+ let out = ctx.fast.join("profile.json");+ let _ = fs::remove_file(&out);+ let ran = run(ctx, &bin, &b, &[("FAST_ANYTHING_PROF_OUT", &out)], true)?;+ ensure!(ran.status.success(), "the app failed ({}):\n{}", ran.status, tail(&combined(&ran), 30));+ let result: Value = serde_json::from_str(+ &fs::read_to_string(&out).context("the profiler wrote nothing: does main return normally?")?,+ )?;+ let wall = result["wall"].as_f64().unwrap_or(0.0);+ let stats = result["stats"].as_object().cloned().unwrap_or_default();+ let stat = |i: usize| stats.get(&i.to_string()).and_then(Value::as_array).cloned();+ let mut functions = Vec::new();+ for (i, d) in found.iter().enumerate() {+ let helper = found+ .iter()+ .enumerate()+ .any(|(j, g)| stat(j).is_some() && g.path == d.path && g.hs.calls.contains(&d.f.name));+ let mut hs = d.hs.clone();+ match stat(i) {+ Some(s) => {+ hs.ncalls = s[0].as_u64().unwrap_or(0);+ hs.tottime = s[1].as_f64().unwrap_or(0.0);+ hs.cumtime = s[2].as_f64().unwrap_or(0.0);+ functions.push(hs);+ }+ None if helper => functions.push(hs),+ None => {}+ }+ }+ Ok(Profile { wall, base: ".".into(), functions })+}++// ------------------------------------------------------------------ recording++fn arg_names(hs: &Hotspot) -> Vec<String> {+ hs.params.iter().map(|p| p.name.clone()).collect()+}++fn c_put(kind: &CKind, name: &str, params: &[Param], sub: Option<(usize, &str)>, idx: usize) -> String {+ let value = |i: usize, n: &str| match sub {+ Some((k, v)) if k == i => v.to_string(),+ _ => n.to_string(),+ };+ let v = value(idx, name);+ match kind {+ CKind::Scalar(Scalar::Int { signed: true, .. }) | CKind::Len => format!("fa_rec_i64((long long) ({v}));"),+ CKind::Scalar(Scalar::Int { signed: false, .. }) => format!("fa_rec_u64((unsigned long long) ({v}));"),+ CKind::Scalar(Scalar::Float(_)) => format!("fa_rec_f64((double) ({v}));"),+ CKind::Scalar(Scalar::Bool) => format!("fa_rec_bool((int) ({v}));"),+ CKind::Str => format!("fa_rec_str({v});"),+ CKind::Array(s, len) => {+ let n = value(*len, ¶ms[*len].name);+ match s {+ Scalar::Float(_) => format!("fa_rec_arr_f64({v}, (size_t) ({n}), (int) sizeof(*({v})));"),+ Scalar::Int { signed, .. } => {+ format!("fa_rec_arr_i64({v}, (size_t) ({n}), (int) sizeof(*({v})), {});", i32::from(*signed))+ }+ Scalar::Bool => format!("fa_rec_arr_i64({v}, (size_t) ({n}), (int) sizeof(*({v})), 0);"),+ }+ }+ }+}++fn c_suffix(ret: &str) -> &'static str {+ match scalar(ret) {+ Some(Scalar::Int { signed: false, .. }) => "u64",+ Some(Scalar::Int { .. }) => "i64",+ Some(Scalar::Float(_)) => "f64",+ _ => "bool",+ }+}++fn c_cast(ret: &str) -> &'static str {+ match c_suffix(ret) {+ "u64" => "(unsigned long long)",+ "i64" => "(long long)",+ "f64" => "(double)",+ _ => "(int)",+ }+}++fn c_record_prologue(hs: &Hotspot) -> Result<String> {+ let kinds = c_kinds(&hs.params).map_err(anyhow::Error::msg)?;+ let ret = hs.returns.clone().unwrap_or_default();+ let names = arg_names(hs);+ let puts = |sub: Option<(usize, &str)>| -> String {+ kinds+ .iter()+ .enumerate()+ .filter(|(_, k)| **k != CKind::Len)+ .map(|(i, k)| c_put(k, &names[i], &hs.params, sub, i))+ .collect::<Vec<_>>()+ .join(" ")+ };+ let call = |sub: &[(usize, String)]| -> String {+ let args: Vec<String> = names+ .iter()+ .enumerate()+ .map(|(i, n)| sub.iter().find(|(k, _)| *k == i).map(|(_, v)| v.clone()).unwrap_or_else(|| n.clone()))+ .collect();+ format!("{}({})", hs.name, args.join(", "))+ };+ let (sfx, cast) = (c_suffix(&ret), c_cast(&ret));+ let mut derive = String::new();+ for (i, k) in kinds.iter().enumerate() {+ let (len_expr, sub_val, len_sub, free) = match k {+ CKind::Str => (format!("fa_rec_chars({})", names[i]), "fa_s".to_string(), None, "fa_rec_free(fa_s);"),+ CKind::Array(_, len) => {+ (format!("(size_t) ({})", names[*len]), format!("{} + fa_off", names[i]), Some(*len), "")+ }+ _ => continue,+ };+ let mut subs = vec![(i, sub_val.clone())];+ if let Some(l) = len_sub {+ let lt = hs.params[l].annotation.clone().unwrap_or_else(|| "int".into());+ subs.push((l, format!("({lt}) fa_n")));+ }+ let prep = if matches!(k, CKind::Str) {+ format!("char *fa_s = fa_rec_substr({}, fa_off, fa_n); ", names[i])+ } else {+ String::new()+ };+ // fa_rec_begin + puts with the substitutions (puts takes one substitution: arrays put data + len themselves)+ let put_sub = if matches!(k, CKind::Str) { "fa_s".to_string() } else { sub_val.clone() };+ let mut put_line = String::new();+ for (j, kk) in kinds.iter().enumerate() {+ if *kk == CKind::Len {+ continue;+ }+ let p = match kk {+ CKind::Array(s, len) if j == i => {+ let n = "fa_n";+ match s {+ Scalar::Float(_) => {+ format!("fa_rec_arr_f64({put_sub}, (size_t) {n}, (int) sizeof(*({put_sub})));")+ }+ Scalar::Int { signed, .. } => format!(+ "fa_rec_arr_i64({put_sub}, (size_t) {n}, (int) sizeof(*({put_sub})), {});",+ i32::from(*signed)+ ),+ Scalar::Bool => {+ format!("fa_rec_arr_i64({put_sub}, (size_t) {n}, (int) sizeof(*({put_sub})), 0);")+ }+ }+ .replace("{len}", &len.to_string())+ }+ _ if j == i => c_put(kk, &names[j], &hs.params, Some((j, &put_sub)), j),+ _ => c_put(kk, &names[j], &hs.params, None, j),+ };+ put_line.push_str(&p);+ put_line.push(' ');+ }+ derive.push_str(&format!(+ " for (int fa_k = 0; fa_k < 10 && fa_rec_derive_ok(); fa_k++) {{\n size_t fa_len = {len_expr}, fa_n = (size_t) fa_rec_slices[fa_k];\n if (fa_len < 2 || fa_n >= fa_len) break;\n for (int fa_rep = 0; fa_rep < (fa_n < 2 ? 1 : 3); fa_rep++) {{\n size_t fa_off = fa_rec_rand(fa_len - fa_n + 1);\n {prep}fa_rec_begin(); {put_line}\n fa_rec_derived_{sfx}({cast} {call});\n {free}\n }}\n }}\n",+ call = call(&subs),+ ));+ }+ Ok(format!(+ "if (!fa_rec_inside) {{\n fa_rec_inside = 1;\n fa_rec_begin(); {puts}\n long long fa_t0 = fa_rec_now();\n {ret} fa_r = {call};\n fa_rec_done_{sfx}({cast} fa_r, fa_rec_now() - fa_t0);\n{derive} fa_rec_inside = 0;\n return fa_r;\n}}",+ puts = puts(None),+ call = call(&[]),+ ))+}++fn cpp_record_prologue(hs: &Hotspot) -> String {+ let names = arg_names(hs);+ format!(+ "if (!fa_rec::st().inside) return fa_rec::call([](const auto &...fa_a) {{ return {}(fa_a...); }}{}{});",+ hs.name,+ if names.is_empty() { "" } else { ", " },+ names.join(", ")+ )+}++pub fn record(ctx: &Ctx, cc: &str, args: &[String], hs: &Hotspot, out: &Path, lang: Lang) -> Result<Recording> {+ let b = Build::parse(args)?;+ let found = describe(ctx, &b, lang)?;+ let d = found+ .iter()+ .filter(|d| d.hs.file == hs.file && d.hs.qualname == hs.qualname)+ .min_by_key(|d| (d.hs.line as i64 - hs.line as i64).abs())+ .with_context(|| format!("{} isn't in {} any more: scan again", hs.qualname, hs.file))?;+ let cpp = lang == Lang::Cpp || is_cpp_file(&hs.file);+ let dir = runtime_dir(ctx)?;+ let (prologue, header, extra) = if cpp {+ (cpp_record_prologue(hs), dir.join("fa_rec.hpp"), vec![])+ } else {+ (c_record_prologue(hs)?, dir.join("fa_rec.h"), vec![runtime_source(&dir, "fa_rec", REC_C, lang)?])+ };+ let text = fs::read_to_string(&d.path)?;+ let meta = out.with_extension("meta.json");+ let mut patches = Patches::new(ctx)?;+ patches+ .write(&d.path, &insert_at(&text, vec![(d.f.body_open + 1, format!(" {}", prologue.replace('\n', " ")))]))?;+ let bin = compile(ctx, cc, &b, &extra, Some(&header));+ patches.restore()?;+ let bin = bin?;+ let env = [("FAST_ANYTHING_RECORD_OUT", out), ("FAST_ANYTHING_RECORD_META", meta.as_path())];+ let _ = fs::remove_file(&meta);+ let mut ran = run(ctx, &bin, &b, &env, true)?;+ if !ran.status.success() {+ // A shrunk input crashed the original (C has no exceptions): record without them.+ crate::ui::warn("the app crashed on a shrunk input; recording real calls only");+ ran = run(ctx, &bin, &b, &env, false)?;+ }+ 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("nothing was recorded: does main return normally?")?)+ .context("reading the recording summary")+}++// ------------------------------------------------------------------ the crate++pub const FLAVOR_C: Flavor = Flavor {+ lang: Lang::C,+ fence: "c",+ rust_type: rust_type_c,+ default_json: |_| None,+ rules: &[+ "C `int` is `i32`, `long` is `i64` here; unsigned types wrap. Use `wrapping_*` where the original can overflow.",+ "A `const T *` followed by a length arrives as a Vec, and the length parameter still arrives on its own.",+ "`const char *` arrives as a UTF-8 String: `strlen` and `s[i]` are bytes, use `as_bytes()` for the same behavior.",+ "Returns are numbers or bools. Undefined behavior in the original (overflow of signed ints, out-of-bounds reads) isn't a spec: match the defined cases.",+ ],+};++pub const FLAVOR_CPP: Flavor = Flavor {+ lang: Lang::Cpp,+ fence: "cpp",+ rust_type: cpp_rust_type,+ default_json: |_| None,+ rules: &[+ "`int` is `i32`, `long long`/`int64_t` is `i64`, `size_t` is `u64`; unsigned types wrap. Use `wrapping_*` where the original can overflow.",+ "`std::string` arrives as a UTF-8 String: `size()` and `s[i]` are bytes, use `as_bytes()` for the same behavior.",+ "`std::vector` is Vec, `std::array<T, N>` is `[T; N]`, `std::map<std::string, T>` is BTreeMap (same key order), `std::pair` is a tuple.",+ "Return `Err(message)` where the original throws.",+ ],+};++pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {+ native::scaffold(ctx, hs, helpers, port, if port.lang == Lang::Cpp { &FLAVOR_CPP } else { &FLAVOR_C })+}++pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {+ native::verify(ctx, port, false)+}++// ------------------------------------------------------------------ the bridge++fn suffix(port: &Port) -> String {+ util::slug(&port.id)+}++fn c_string_literal(s: &str) -> String {+ format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))+}++fn param_list(hs: &Hotspot) -> String {+ hs.params+ .iter()+ .map(|p| format!("{} {}", p.annotation.as_deref().unwrap_or("int"), p.name))+ .collect::<Vec<_>>()+ .join(", ")+}++const LOADER: &str = "#ifdef _WIN32\n#ifndef WIN32_LEAN_AND_MEAN\n#define WIN32_LEAN_AND_MEAN\n#endif\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include <windows.h>\n#define FA_OPEN(p) ((void *) LoadLibraryA(p))\n#define FA_SYM(l, n) ((void *) GetProcAddress((HMODULE) (l), n))\n#else\n#include <dlfcn.h>\n#define FA_OPEN(p) dlopen(p, RTLD_NOW | RTLD_LOCAL)\n#define FA_SYM(l, n) dlsym(l, n)\n#endif";++fn c_bridge(hs: &Hotspot, s: &str, lib: &str) -> Result<String> {+ let kinds = c_kinds(&hs.params).map_err(anyhow::Error::msg)?;+ let ret = hs.returns.clone().unwrap_or_default();+ let mut puts = String::new();+ let mut first = true;+ for (i, k) in kinds.iter().enumerate() {+ if *k == CKind::Len && i > 0 && matches!(kinds[i - 1], CKind::Array(..)) && false {+ continue;+ }+ let n = &hs.params[i].name;+ if !first {+ puts.push_str(" fa_put_S(&b, \",\");\n");+ }+ first = false;+ puts.push_str(&match k {+ CKind::Scalar(Scalar::Int { signed: true, .. }) | CKind::Len => format!(" fa_int_S(&b, (long long) ({n}));\n"),+ CKind::Scalar(Scalar::Int { signed: false, .. }) => format!(" fa_uint_S(&b, (unsigned long long) ({n}));\n"),+ CKind::Scalar(Scalar::Float(_)) => format!(" if (!fa_dbl_S(&b, (double) ({n}))) goto fallback;\n"),+ CKind::Scalar(Scalar::Bool) => format!(" fa_put_S(&b, ({n}) ? \"true\" : \"false\");\n"),+ CKind::Str => format!(" if (!fa_str_S(&b, {n})) goto fallback;\n"),+ CKind::Array(sc, len) => {+ let l = &hs.params[*len].name;+ let item = match sc {+ Scalar::Float(_) => format!("if (!fa_dbl_S(&b, (double) {n}[fa_i])) goto fallback;"),+ Scalar::Int { signed: true, .. } => format!("fa_int_S(&b, (long long) {n}[fa_i]);"),+ Scalar::Int { signed: false, .. } => format!("fa_uint_S(&b, (unsigned long long) {n}[fa_i]);"),+ Scalar::Bool => format!("fa_put_S(&b, {n}[fa_i] ? \"true\" : \"false\");"),+ };+ format!(" fa_put_S(&b, \"[\");\n for (size_t fa_i = 0; fa_i < (size_t) ({l}); fa_i++) {{ if (fa_i) fa_put_S(&b, \",\"); {item} }}\n fa_put_S(&b, \"]\");\n")+ }+ });+ }+ let parse = match scalar(&ret) {+ Some(Scalar::Bool) => "strncmp(ok, \"true\", 4) == 0".to_string(),+ Some(Scalar::Float(_)) => format!("({ret}) strtod(ok, NULL)"),+ Some(Scalar::Int { signed: false, .. }) => format!("({ret}) strtoull(ok, NULL, 10)"),+ _ => format!("({ret}) strtoll(ok, NULL, 10)"),+ };+ let body = format!(+ r#"/* Calls the verified Rust port of {id}. FAST_ANYTHING_DISABLE=1 runs the C version instead. */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+{loader}+typedef struct {{ char *p; size_t len, cap; }} fa_buf_S;+static unsigned char *(*fa_call_S)(const unsigned char *, size_t, size_t *);+static void (*fa_free_S)(unsigned char *, size_t);+int fa_on_S(void) {{+ static int state = -1;+ if (state < 0) {{+ void *lib = getenv("FAST_ANYTHING_DISABLE") ? NULL : FA_OPEN({lib});+ state = 0;+ if (lib) {{+ *(void **) &fa_call_S = FA_SYM(lib, "fa_call");+ *(void **) &fa_free_S = FA_SYM(lib, "fa_free");+ state = fa_call_S && fa_free_S;+ }}+ }}+ return state;+}}+static void fa_put_S(fa_buf_S *b, const char *s) {{+ size_t n = strlen(s);+ if (b->len + n + 1 > b->cap) {{ b->cap = (b->len + n + 1) * 2; b->p = (char *) realloc(b->p, b->cap); }}+ memcpy(b->p + b->len, s, n + 1);+ b->len += n;+}}+static void fa_int_S(fa_buf_S *b, long long v) {{ char t[32]; snprintf(t, sizeof t, "%lld", v); fa_put_S(b, t); }}+static void fa_uint_S(fa_buf_S *b, unsigned long long v) {{ char t[32]; snprintf(t, sizeof t, "%llu", v); fa_put_S(b, t); }}+static int fa_dbl_S(fa_buf_S *b, double v) {{+ char t[40];+ if (!isfinite(v)) return 0;+ snprintf(t, sizeof t, "%.17g", v);+ fa_put_S(b, t);+ return 1;+}}+static int fa_str_S(fa_buf_S *b, const char *s) {{+ char t[8] = {{0}};+ if (!s) {{ fa_put_S(b, "null"); return 1; }}+ fa_put_S(b, "\"");+ for (; *s; s++) {{+ unsigned char c = (unsigned char) *s;+ if (c == '"' || c == '\\') {{ t[0] = '\\'; t[1] = (char) c; t[2] = 0; }}+ else if (c < 0x20) snprintf(t, sizeof t, "\\u%04x", c);+ else {{ t[0] = (char) c; t[1] = 0; }}+ fa_put_S(b, t);+ }}+ fa_put_S(b, "\"");+ return 1;+}}+/* Sets *fa_ok to 0 (and the C version runs) if the port can't answer. */+{ret} fa_fast_S(int *fa_ok, {params}) {{+ fa_buf_S b = {{0}};+ size_t n = 0;+ unsigned char *out;+ char *text;+ const char *ok;+ {ret} r = 0;+ *fa_ok = 0;+ fa_put_S(&b, "[");+{puts} fa_put_S(&b, "]");+ out = fa_call_S((const unsigned char *) b.p, b.len, &n);+ text = (char *) malloc(n + 1);+ memcpy(text, out, n);+ text[n] = 0;+ fa_free_S(out, n);+ ok = strstr(text, "\"ok\":");+ if (ok) {{+ ok += 5;+ r = {parse};+ *fa_ok = 1;+ }}+ free(text);+fallback:+ free(b.p);+ return r;+}}"#,+ id = hs.id,+ loader = LOADER,+ params = param_list(hs),+ );+ Ok(body.replace("_S", &format!("_{s}")))+}++fn cpp_bridge(hs: &Hotspot, s: &str, lib: &str, namespaces: &[String]) -> String {+ let ret = hs.returns.clone().unwrap_or_default();+ let open: String = namespaces+ .iter()+ .map(|n| if n.is_empty() { "namespace {\n".to_string() } else { format!("namespace {n} {{\n") })+ .collect();+ let close: String = namespaces.iter().map(|_| "}\n").collect();+ let body = format!(+ r#"// Calls the verified Rust port of {id}. FAST_ANYTHING_DISABLE=1 runs the C++ version instead.+#include <algorithm>+#include <array>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <map>+#include <stdexcept>+#include <string>+#include <type_traits>+#include <unordered_map>+#include <utility>+#include <vector>+{loader}+namespace fa_bridge_S {{+{json}+struct Lib {{+ unsigned char *(*call)(const unsigned char *, size_t, size_t *) = nullptr;+ void (*free)(unsigned char *, size_t) = nullptr;+ bool on = false;+ Lib() {{+ if (std::getenv("FAST_ANYTHING_DISABLE")) return;+ void *lib = FA_OPEN({lib});+ if (!lib) return;+ *(void **) &call = FA_SYM(lib, "fa_call");+ *(void **) &free = FA_SYM(lib, "fa_free");+ on = call && free;+ }}+}};+inline Lib &lib() {{ static Lib l; return l; }}+}} // namespace fa_bridge_S+{open}bool fa_on_S() {{ return fa_bridge_S::lib().on; }}+bool fa_fast_S({ret} &fa_out, {params}) {{+ std::string in = "[";+ if (!fa_bridge_S::enc_all(in, {args})) return false;+ in += "]";+ size_t n = 0;+ unsigned char *out = fa_bridge_S::lib().call((const unsigned char *) in.data(), in.size(), &n);+ std::string text((const char *) out, n);+ fa_bridge_S::lib().free(out, n);+ const char *p = text.c_str();+ fa_bridge_S::V reply = fa_bridge_S::parse(p);+ if (const fa_bridge_S::V *err = reply.get("error")) throw std::runtime_error("fast-anything: " + err->s);+ const fa_bridge_S::V *ok = reply.get("ok");+ if (!ok) return false;+ fa_bridge_S::from(*ok, fa_out);+ return true;+}}+{close}"#,+ id = hs.id,+ loader = LOADER,+ json = JSON_HPP,+ params = param_list(hs),+ args = arg_names(hs).join(", "),+ );+ body.replace("_S", &format!("_{s}"))+}++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(&call) || l.contains(&spaced)) && !l.trim_end().ends_with(';'))+ }+}++pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {+ let hs = ctx+ .state+ .hotspots+ .iter()+ .find(|h| h.id == port.id)+ .with_context(|| format!("{} isn't in the last scan", port.id))?;+ let file = ctx.root.join(&port.file);+ let text = fs::read_to_string(&file).with_context(|| format!("reading {}", port.file))?;+ let cpp = port.lang == Lang::Cpp || is_cpp_file(&port.file);+ let s = suffix(port);+ let (_, lib) = port.lang.artifact(&port.ext);+ let lib = c_string_literal(&util::forward_slashes(&ctx.lib_dir().join(lib)));+ let ret = hs.returns.clone().unwrap_or_default();+ let args = arg_names(hs).join(", ");+ let (prologue, bridge) = if cpp {+ let namespaces = parse(&text)+ .into_iter()+ .find(|f| f.name == hs.name && f.class == hs.owner)+ .map(|f| f.namespaces)+ .unwrap_or_default();+ (+ format!(+ "bool fa_on_{s}();\nbool fa_fast_{s}({ret} &, {params});\nif (fa_on_{s}()) {{\n {ret} fa_r{{}};\n if (fa_fast_{s}(fa_r, {args})) return fa_r;\n}}",+ params = param_list(hs)+ ),+ cpp_bridge(hs, &s, &lib, &namespaces),+ )+ } else {+ (+ format!(+ "int fa_on_{s}(void);\n{ret} fa_fast_{s}(int *, {params});\nif (fa_on_{s}()) {{\n int fa_ok;\n {ret} fa_r = fa_fast_{s}(&fa_ok, {args});\n if (fa_ok) return fa_r;\n}}",+ params = param_list(hs)+ ),+ c_bridge(hs, &s, &lib)?,+ )+ };+ let patched = native::insert_in_body(&text, "//", &port.id, &prologue, find_body(&port.func, port.line.max(1)))?;+ let patched = backend::append_marked(&patched, "//", &format!("{} bridge", port.id), &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))?;+ let text = native::strip_in_body(&text, "//", &port.id);+ let text = backend::strip_marked(&text, "//", &format!("{} bridge", port.id));+ fs::write(&file, text).with_context(|| format!("writing {}", port.file))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn finds_c_and_cpp_functions() {+ let c = "#include <stdio.h>\n/* a { comment */\nstatic int lev(const char *a, const char *b) {\n return 0;\n}\n\nlong count(const int *xs, size_t n, int max)\n{\n if (n) { return 1; }\n printf(\"{\");\n return 0;\n}\nint main(void) { return lev(\"a\", \"b\"); }\n";+ let f = parse(c);+ assert_eq!(f.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["lev", "count", "main"]);+ assert_eq!(f[0].ret, "int");+ assert!(f[0].is_static);+ assert_eq!(+ c_kinds(&f[1].params).unwrap(),+ vec![CKind::Array(scalar("int").unwrap(), 1), CKind::Len, CKind::Scalar(scalar("int").unwrap())]+ );+ let cpp = "namespace text {\nclass Fuzzy {\npublic:\n static std::vector<std::pair<int, int>> find(const std::vector<std::string> &names, int max = 2) {\n return {};\n }\n int size() const { return 0; }\n};\n}\n";+ let f = parse(cpp);+ assert_eq!(f.len(), 2);+ assert_eq!(f[0].class.as_deref(), Some("Fuzzy"));+ assert_eq!(f[0].namespaces, ["text"]);+ assert_eq!(f[0].params[1].default.as_deref(), Some("2"));+ assert_eq!(cpp_rust_type(&f[0].ret).as_deref(), Some("Vec<(i32, i32)>"));+ assert_eq!(cpp_rust_type("const std::vector<std::string>&").as_deref(), Some("Vec<String>"));+ assert_eq!(detect("clang++"), Some(Lang::Cpp));+ assert_eq!(detect("/usr/bin/gcc-14"), Some(Lang::C));+ assert_eq!(detect("clang-cl"), None.or(detect("clang-cl")));+ let b =+ Build::parse(&["-O2".into(), "main.c".into(), "-o".into(), "app".into(), "--".into(), "x".into()]).unwrap();+ assert_eq!(+ (b.flags, b.sources, b.args),+ (vec!["-O2".to_string()], vec!["main.c".to_string()], vec!["x".to_string()])+ );+ }+}diff --git a/src/cfamily/clock.h b/src/cfamily/clock.hnew file mode 100644index 0000000..edf7cb7--- /dev/null+++ b/src/cfamily/clock.h@@ -0,0 +1,24 @@+/* fast-anything: a monotonic clock in nanoseconds, for the profiler and the recorder. */+#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+static long long fa_now(void) {+ static LARGE_INTEGER freq;+ LARGE_INTEGER c;+ if (!freq.QuadPart) QueryPerformanceFrequency(&freq);+ QueryPerformanceCounter(&c);+ return (long long) ((double) c.QuadPart * 1e9 / (double) freq.QuadPart);+}+#else+#include <time.h>+static long long fa_now(void) {+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return (long long) ts.tv_sec * 1000000000LL + ts.tv_nsec;+}+#endifdiff --git a/src/cfamily/json.hpp b/src/cfamily/json.hppnew file mode 100644index 0000000..a3474d8--- /dev/null+++ b/src/cfamily/json.hpp@@ -0,0 +1,197 @@+// ---- JSON for fast-anything's C++ recorder and bridge (C++14). Generated; don't edit.+inline bool fa_utf8(const std::string &s) {+ size_t i = 0;+ while (i < s.size()) {+ unsigned char c = (unsigned char) s[i];+ int n = c < 0x80 ? 0 : (c >> 5) == 6 ? 1 : (c >> 4) == 14 ? 2 : (c >> 3) == 30 ? 3 : -1;+ if (n < 0 || i + n >= s.size() + (n == 0)) return n == 0;+ for (int k = 1; k <= n; k++)+ if (((unsigned char) s[i + k] & 0xC0) != 0x80) return false;+ i += n + 1;+ }+ return true;+}+inline bool enc_str(std::string &o, const std::string &s) {+ if (!fa_utf8(s)) return false;+ o += '"';+ for (unsigned char c : s) {+ if (c == '"' || c == '\\') { o += '\\'; o += (char) c; }+ else if (c < 0x20) { char t[8]; std::snprintf(t, sizeof t, "\\u%04x", c); o += t; }+ else o += (char) c;+ }+ o += '"';+ return true;+}+inline bool enc(std::string &o, bool v) { o += v ? "true" : "false"; return true; }+template <class T> typename std::enable_if<std::is_integral<T>::value, bool>::type enc(std::string &o, T v) { o += std::to_string(v); return true; }+template <class T> typename std::enable_if<std::is_floating_point<T>::value, bool>::type enc(std::string &o, T v) {+ if (!std::isfinite((double) v)) return false;+ char t[40];+ std::snprintf(t, sizeof t, "%.17g", (double) v);+ if (!std::strpbrk(t, ".eE")) std::strcat(t, ".0");+ o += t;+ return true;+}+inline bool enc(std::string &o, const std::string &v) { return enc_str(o, v); }+inline bool enc(std::string &o, const char *v) { if (!v) { o += "null"; return true; } return enc_str(o, v); }+template <class A, class B> bool enc(std::string &o, const std::pair<A, B> &v);+template <class T, class Al> bool enc(std::string &o, const std::vector<T, Al> &v);+template <class T, size_t N> bool enc(std::string &o, const std::array<T, N> &v);+template <class T, class C, class Al> bool enc(std::string &o, const std::map<std::string, T, C, Al> &v);+template <class T, class H, class E, class Al> bool enc(std::string &o, const std::unordered_map<std::string, T, H, E, Al> &v);+template <class It> bool enc_seq(std::string &o, It a, It b) {+ o += '[';+ for (It i = a; i != b; ++i) {+ if (i != a) o += ',';+ if (!enc(o, *i)) return false;+ }+ o += ']';+ return true;+}+template <class T, class Al> bool enc(std::string &o, const std::vector<T, Al> &v) { return enc_seq(o, v.begin(), v.end()); }+template <class T, size_t N> bool enc(std::string &o, const std::array<T, N> &v) { return enc_seq(o, v.begin(), v.end()); }+template <class A, class B> bool enc(std::string &o, const std::pair<A, B> &v) {+ o += '[';+ if (!enc(o, v.first)) return false;+ o += ',';+ if (!enc(o, v.second)) return false;+ o += ']';+ return true;+}+template <class M> bool enc_map(std::string &o, const M &m) {+ std::vector<const std::string *> keys;+ for (auto &kv : m) keys.push_back(&kv.first);+ std::sort(keys.begin(), keys.end(), [](const std::string *a, const std::string *b) { return *a < *b; });+ o += '{';+ for (size_t i = 0; i < keys.size(); i++) {+ if (i) o += ',';+ if (!enc_str(o, *keys[i])) return false;+ o += ':';+ if (!enc(o, m.at(*keys[i]))) return false;+ }+ o += '}';+ return true;+}+template <class T, class C, class Al> bool enc(std::string &o, const std::map<std::string, T, C, Al> &v) { return enc_map(o, v); }+template <class T, class H, class E, class Al> bool enc(std::string &o, const std::unordered_map<std::string, T, H, E, Al> &v) { return enc_map(o, v); }+inline bool enc_all(std::string &) { return true; }+template <class A, class... R> bool enc_all(std::string &o, const A &a, const R &...r) {+ if (o.size() > 1) o += ',';+ return enc(o, a) && enc_all(o, r...);+}++// a small DOM, for the bridge's replies+struct V {+ int kind = 0; // 0 null, 1 bool, 2 number, 3 string, 4 array, 5 object+ bool b = false;+ double num = 0;+ long long i = 0;+ bool is_int = false;+ std::string s;+ std::vector<V> arr;+ std::vector<std::pair<std::string, V>> obj;+ const V *get(const char *k) const {+ for (auto &kv : obj)+ if (kv.first == k) return &kv.second;+ return nullptr;+ }+};+inline void ws(const char *&p) { while (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t') p++; }+inline V parse(const char *&p) {+ V v;+ ws(p);+ if (*p == '{') {+ v.kind = 5;+ p++;+ ws(p);+ if (*p == '}') { p++; return v; }+ while (true) {+ ws(p);+ V k = parse(p);+ ws(p);+ p++; // :+ v.obj.emplace_back(k.s, parse(p));+ ws(p);+ if (*p++ == '}') return v;+ }+ }+ if (*p == '[') {+ v.kind = 4;+ p++;+ ws(p);+ if (*p == ']') { p++; return v; }+ while (true) {+ v.arr.push_back(parse(p));+ ws(p);+ if (*p++ == ']') return v;+ }+ }+ if (*p == '"') {+ v.kind = 3;+ p++;+ while (*p && *p != '"') {+ if (*p != '\\') { v.s += *p++; continue; }+ p++;+ char e = *p++;+ if (e == 'n') v.s += '\n';+ else if (e == 't') v.s += '\t';+ else if (e == 'r') v.s += '\r';+ else if (e == 'b') v.s += '\b';+ else if (e == 'f') v.s += '\f';+ else if (e == 'u') {+ unsigned cp = (unsigned) std::strtoul(std::string(p, 4).c_str(), nullptr, 16);+ p += 4;+ if (cp >= 0xD800 && cp < 0xDC00 && p[0] == '\\' && p[1] == 'u') {+ unsigned lo = (unsigned) std::strtoul(std::string(p + 2, 4).c_str(), nullptr, 16);+ p += 6;+ cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);+ }+ if (cp < 0x80) v.s += (char) cp;+ else if (cp < 0x800) { v.s += (char) (0xC0 | (cp >> 6)); v.s += (char) (0x80 | (cp & 63)); }+ else if (cp < 0x10000) { v.s += (char) (0xE0 | (cp >> 12)); v.s += (char) (0x80 | ((cp >> 6) & 63)); v.s += (char) (0x80 | (cp & 63)); }+ else { v.s += (char) (0xF0 | (cp >> 18)); v.s += (char) (0x80 | ((cp >> 12) & 63)); v.s += (char) (0x80 | ((cp >> 6) & 63)); v.s += (char) (0x80 | (cp & 63)); }+ } else v.s += e;+ }+ p++;+ return v;+ }+ if (std::strncmp(p, "true", 4) == 0) { v.kind = 1; v.b = true; p += 4; return v; }+ if (std::strncmp(p, "false", 5) == 0) { v.kind = 1; p += 5; return v; }+ if (std::strncmp(p, "null", 4) == 0) { p += 4; return v; }+ v.kind = 2;+ const char *start = p;+ while (*p && std::strchr("+-0123456789.eE", *p)) p++;+ std::string num(start, p);+ v.is_int = num.find_first_of(".eE") == std::string::npos;+ v.num = std::strtod(num.c_str(), nullptr);+ v.i = v.is_int ? std::strtoll(num.c_str(), nullptr, 10) : (long long) v.num;+ return v;+}+inline void from(const V &v, bool &out) { out = v.b; }+template <class T> typename std::enable_if<std::is_integral<T>::value>::type from(const V &v, T &out) { out = (T) (v.is_int ? v.i : (long long) v.num); }+template <class T> typename std::enable_if<std::is_floating_point<T>::value>::type from(const V &v, T &out) { out = (T) (v.is_int ? (double) v.i : v.num); }+inline void from(const V &v, std::string &out) { out = v.s; }+template <class A, class B> void from(const V &v, std::pair<A, B> &out);+template <class T, class Al> void from(const V &v, std::vector<T, Al> &out);+template <class T, size_t N> void from(const V &v, std::array<T, N> &out);+template <class T, class C, class Al> void from(const V &v, std::map<std::string, T, C, Al> &out);+template <class T, class H, class E, class Al> void from(const V &v, std::unordered_map<std::string, T, H, E, Al> &out);+template <class T, class Al> void from(const V &v, std::vector<T, Al> &out) {+ out.clear();+ out.reserve(v.arr.size());+ for (auto &x : v.arr) { T t{}; from(x, t); out.push_back(std::move(t)); }+}+template <class T, size_t N> void from(const V &v, std::array<T, N> &out) {+ for (size_t i = 0; i < N && i < v.arr.size(); i++) from(v.arr[i], out[i]);+}+template <class A, class B> void from(const V &v, std::pair<A, B> &out) {+ if (v.arr.size() == 2) { from(v.arr[0], out.first); from(v.arr[1], out.second); }+}+template <class T, class C, class Al> void from(const V &v, std::map<std::string, T, C, Al> &out) {+ out.clear();+ for (auto &kv : v.obj) { T t{}; from(kv.second, t); out.emplace(kv.first, std::move(t)); }+}+template <class T, class H, class E, class Al> void from(const V &v, std::unordered_map<std::string, T, H, E, Al> &out) {+ out.clear();+ for (auto &kv : v.obj) { T t{}; from(kv.second, t); out.emplace(kv.first, std::move(t)); }+}diff --git a/src/cfamily/prof.c b/src/cfamily/prof.cnew file mode 100644index 0000000..5224c81--- /dev/null+++ b/src/cfamily/prof.c@@ -0,0 +1,61 @@+/* fast-anything profiler runtime: compiled into the app for one run. */+#include <stdio.h>+#include <stdlib.h>+#include "fa_clock.h"+#include "fa_prof.h"++#define FA_MAX 65536+typedef struct { long long calls, own, cum; int active; } fa_stat;+static fa_stat fa_stats[FA_MAX];+static __thread long long fa_children[1024];+static __thread int fa_depth;+static long long fa_started;++#ifdef __cplusplus+extern "C" {+#endif+fa_prof_frame fa_prof_enter(int id) {+ fa_prof_frame f;+ f.id = id;+ if (id >= 0 && id < FA_MAX) fa_stats[id].active++;+ if (fa_depth < 1024) fa_children[fa_depth] = 0;+ fa_depth++;+ f.t = fa_now();+ return f;+}++void fa_prof_exit(fa_prof_frame *f) {+ long long took = fa_now() - f->t;+ fa_depth--;+ long long children = fa_depth < 1024 ? fa_children[fa_depth] : 0;+ if (f->id >= 0 && f->id < FA_MAX) {+ fa_stat *s = &fa_stats[f->id];+ s->calls++;+ s->own += took - children;+ if (--s->active == 0) s->cum += took;+ }+ if (fa_depth > 0 && fa_depth <= 1024) fa_children[fa_depth - 1] += took;+}+#ifdef __cplusplus+}+#endif++static void fa_prof_save(void) {+ const char *path = getenv("FAST_ANYTHING_PROF_OUT");+ FILE *out = path ? fopen(path, "wb") : NULL;+ if (!out) return;+ fprintf(out, "{\"wall\":%.9f,\"stats\":{", (double) (fa_now() - fa_started) / 1e9);+ int first = 1;+ for (int i = 0; i < FA_MAX; i++) {+ if (!fa_stats[i].calls) continue;+ fprintf(out, "%s\"%d\":[%lld,%.9f,%.9f]", first ? "" : ",", i, fa_stats[i].calls, (double) fa_stats[i].own / 1e9, (double) fa_stats[i].cum / 1e9);+ first = 0;+ }+ fprintf(out, "}}");+ fclose(out);+}++__attribute__((constructor)) static void fa_prof_start(void) {+ fa_started = fa_now();+ atexit(fa_prof_save);+}diff --git a/src/cfamily/prof.h b/src/cfamily/prof.hnew file mode 100644index 0000000..c4869a8--- /dev/null+++ b/src/cfamily/prof.h@@ -0,0 +1,14 @@+/* fast-anything profiler for one run: force-included with -include, removed afterwards. */+#ifndef FAST_ANYTHING_PROF_H+#define FAST_ANYTHING_PROF_H+#ifdef __cplusplus+extern "C" {+#endif+typedef struct { int id; long long t; } fa_prof_frame;+fa_prof_frame fa_prof_enter(int id);+void fa_prof_exit(fa_prof_frame *f);+#ifdef __cplusplus+}+#endif+#define FA_PROF(id) __attribute__((cleanup(fa_prof_exit))) fa_prof_frame fa_prof_frame_ = fa_prof_enter(id)+#endifdiff --git a/src/cfamily/rec.c b/src/cfamily/rec.cnew file mode 100644index 0000000..49759e5--- /dev/null+++ b/src/cfamily/rec.c@@ -0,0 +1,244 @@+/* fast-anything recorder runtime for C: compiled into the app for one run. */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include "fa_clock.h"+#include "fa_rec.h"++int fa_rec_inside;+const int fa_rec_slices[10] = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55};++typedef struct { char *p; size_t len, cap; } fa_buf;+static fa_buf fa_args, fa_line;+static char **fa_kept, **fa_derived;+static size_t fa_nkept, fa_nderived, fa_limit;+static long long fa_calls, fa_skipped, fa_nanos, fa_derive_started;+static int fa_bad; /* the current call has something JSON can't hold */+static unsigned long long fa_rng = 0xFA57;++static void fa_put(fa_buf *b, const char *s, size_t n) {+ if (b->len + n + 1 > b->cap) {+ b->cap = (b->len + n + 1) * 2;+ b->p = (char *) realloc(b->p, b->cap);+ }+ memcpy(b->p + b->len, s, n);+ b->len += n;+ b->p[b->len] = 0;+}+static void fa_puts(fa_buf *b, const char *s) { fa_put(b, s, strlen(s)); }+static void fa_sep(void) {+ if (fa_args.len > 1) fa_puts(&fa_args, ",");+}++long long fa_rec_now(void) { return fa_now(); }+void fa_rec_begin(void) {+ fa_args.len = 0;+ fa_bad = 0;+ fa_puts(&fa_args, "[");+}+void fa_rec_i64(long long v) {+ char t[32];+ fa_sep();+ snprintf(t, sizeof t, "%lld", v);+ fa_puts(&fa_args, t);+}+void fa_rec_u64(unsigned long long v) {+ char t[32];+ fa_sep();+ snprintf(t, sizeof t, "%llu", v);+ fa_puts(&fa_args, t);+}+static void fa_f64_to(fa_buf *b, double v) {+ char t[40];+ if (!isfinite(v)) {+ fa_bad = 1;+ fa_puts(b, "null");+ return;+ }+ snprintf(t, sizeof t, "%.17g", v);+ if (!strpbrk(t, ".eE")) strcat(t, ".0");+ fa_puts(b, t);+}+void fa_rec_f64(double v) {+ fa_sep();+ fa_f64_to(&fa_args, v);+}+void fa_rec_bool(int v) {+ fa_sep();+ fa_puts(&fa_args, v ? "true" : "false");+}+static int fa_utf8_ok(const unsigned char *s) {+ while (*s) {+ int n = *s < 0x80 ? 0 : (*s >> 5) == 6 ? 1 : (*s >> 4) == 14 ? 2 : (*s >> 3) == 30 ? 3 : -1;+ if (n < 0) return 0;+ s++;+ while (n--) {+ if ((*s & 0xC0) != 0x80) return 0;+ s++;+ }+ }+ return 1;+}+void fa_rec_str(const char *s) {+ fa_sep();+ if (!s) {+ fa_puts(&fa_args, "null");+ return;+ }+ if (!fa_utf8_ok((const unsigned char *) s)) fa_bad = 1;+ fa_puts(&fa_args, "\"");+ for (const unsigned char *c = (const unsigned char *) s; *c; c++) {+ char t[8];+ if (*c == '"' || *c == '\\') {+ t[0] = '\\';+ t[1] = (char) *c;+ fa_put(&fa_args, t, 2);+ } else if (*c < 0x20) {+ snprintf(t, sizeof t, "\\u%04x", *c);+ fa_puts(&fa_args, t);+ } else {+ fa_put(&fa_args, (const char *) c, 1);+ }+ }+ fa_puts(&fa_args, "\"");+}+void fa_rec_arr_i64(const void *p, size_t n, int size, int is_signed) {+ fa_sep();+ fa_puts(&fa_args, "[");+ for (size_t i = 0; i < n; i++) {+ char t[32];+ const char *e = (const char *) p + i * size;+ if (is_signed) {+ long long v = size == 1 ? *(const signed char *) e : size == 2 ? *(const short *) e : size == 4 ? *(const int *) e : *(const long long *) e;+ snprintf(t, sizeof t, "%s%lld", i ? "," : "", v);+ } else {+ unsigned long long v = size == 1 ? *(const unsigned char *) e : size == 2 ? *(const unsigned short *) e : size == 4 ? *(const unsigned *) e : *(const unsigned long long *) e;+ snprintf(t, sizeof t, "%s%llu", i ? "," : "", v);+ }+ fa_puts(&fa_args, t);+ }+ fa_puts(&fa_args, "]");+}+void fa_rec_arr_f64(const void *p, size_t n, int size) {+ fa_sep();+ fa_puts(&fa_args, "[");+ for (size_t i = 0; i < n; i++) {+ if (i) fa_puts(&fa_args, ",");+ fa_f64_to(&fa_args, size == 4 ? (double) ((const float *) p)[i] : ((const double *) p)[i]);+ }+ fa_puts(&fa_args, "]");+}++static unsigned long long fa_next(void) {+ fa_rng ^= fa_rng << 13;+ fa_rng ^= fa_rng >> 7;+ fa_rng ^= fa_rng << 17;+ return fa_rng;+}+size_t fa_rec_rand(size_t below) { return below ? (size_t) (fa_next() % below) : 0; }++static char *fa_finish(const char *result, int derived) {+ fa_line.len = 0;+ fa_puts(&fa_line, "{\"args\":");+ fa_puts(&fa_line, fa_args.p);+ fa_puts(&fa_line, "],\"result\":");+ fa_puts(&fa_line, result);+ fa_puts(&fa_line, derived ? ",\"derived\":true}" : "}");+ char *copy = (char *) malloc(fa_line.len + 1);+ memcpy(copy, fa_line.p, fa_line.len + 1);+ return copy;+}+static void fa_keep(const char *result, long long took) {+ if (!fa_limit) {+ const char *l = getenv("FAST_ANYTHING_RECORD_LIMIT");+ fa_limit = l && atoi(l) > 0 ? (size_t) atoi(l) : 500;+ fa_kept = (char **) calloc(fa_limit, sizeof(char *));+ }+ fa_calls++;+ fa_nanos += took;+ if (fa_bad) {+ fa_skipped++;+ return;+ }+ size_t slot = fa_nkept < fa_limit ? fa_nkept : (size_t) (fa_next() % (unsigned long long) fa_calls);+ if (slot >= fa_limit) return;+ char *line = fa_finish(result, 0);+ if (slot < fa_nkept) {+ free(fa_kept[slot]);+ } else {+ fa_nkept++;+ }+ fa_kept[slot] = line;+}+static void fa_derive(const char *result) {+ if (fa_bad) return;+ fa_derived = (char **) realloc(fa_derived, (fa_nderived + 1) * sizeof(char *));+ fa_derived[fa_nderived++] = fa_finish(result, 1);+}+static const char *fa_fmt_i64(long long r) { static char t[32]; snprintf(t, sizeof t, "%lld", r); return t; }+static const char *fa_fmt_u64(unsigned long long r) { static char t[32]; snprintf(t, sizeof t, "%llu", r); return t; }+static const char *fa_fmt_f64(double r) {+ static fa_buf b;+ b.len = 0;+ fa_f64_to(&b, r);+ return b.p;+}+void fa_rec_done_i64(long long r, long long took) { fa_keep(fa_fmt_i64(r), took); }+void fa_rec_done_u64(unsigned long long r, long long took) { fa_keep(fa_fmt_u64(r), took); }+void fa_rec_done_f64(double r, long long took) { fa_keep(fa_fmt_f64(r), took); }+void fa_rec_done_bool(int r, long long took) { fa_keep(r ? "true" : "false", took); }+void fa_rec_derived_i64(long long r) { fa_derive(fa_fmt_i64(r)); }+void fa_rec_derived_u64(unsigned long long r) { fa_derive(fa_fmt_u64(r)); }+void fa_rec_derived_f64(double r) { fa_derive(fa_fmt_f64(r)); }+void fa_rec_derived_bool(int r) { fa_derive(r ? "true" : "false"); }++int fa_rec_derive_ok(void) {+ const char *d = getenv("FAST_ANYTHING_RECORD_DERIVE");+ if (d && d[0] == '0') return 0;+ if (!fa_derive_started) fa_derive_started = fa_now();+ return fa_nderived < 200 && fa_now() - fa_derive_started < 3000000000LL;+}++size_t fa_rec_chars(const char *s) {+ size_t n = 0;+ for (; *s; s++) n += ((unsigned char) *s & 0xC0) != 0x80;+ return n;+}+char *fa_rec_substr(const char *s, size_t off, size_t len) {+ const char *a = s;+ while (*a && off) {+ a++;+ while (((unsigned char) *a & 0xC0) == 0x80) a++;+ off--;+ }+ const char *b = a;+ while (*b && len) {+ b++;+ while (((unsigned char) *b & 0xC0) == 0x80) b++;+ len--;+ }+ char *out = (char *) malloc((size_t) (b - a) + 1);+ memcpy(out, a, (size_t) (b - a));+ out[b - a] = 0;+ return out;+}+void fa_rec_free(void *p) { free(p); }++static void fa_rec_save(void) {+ const char *path = getenv("FAST_ANYTHING_RECORD_OUT"), *meta = getenv("FAST_ANYTHING_RECORD_META");+ FILE *out = path ? fopen(path, "wb") : NULL;+ if (out) {+ for (size_t i = 0; i < fa_nkept; i++) fprintf(out, "%s\n", fa_kept[i]);+ for (size_t i = 0; i < fa_nderived; i++) fprintf(out, "%s\n", fa_derived[i]);+ fclose(out);+ }+ FILE *m = meta ? fopen(meta, "wb") : NULL;+ if (m) {+ fprintf(m, "{\"calls\":%lld,\"kept\":%zu,\"skipped\":%lld,\"unsupported\":[%s],\"original_ns\":%.3f}", fa_calls, fa_nkept,+ fa_skipped, fa_skipped ? "\"NaN, infinity or a string that isn't UTF-8\"" : "", fa_calls ? (double) fa_nanos / (double) fa_calls : 0.0);+ fclose(m);+ }+}++__attribute__((constructor)) static void fa_rec_start(void) { atexit(fa_rec_save); }diff --git a/src/cfamily/rec.h b/src/cfamily/rec.hnew file mode 100644index 0000000..948c36e--- /dev/null+++ b/src/cfamily/rec.h@@ -0,0 +1,36 @@+/* fast-anything recorder for C, force-included with -include for one run. */+#ifndef FAST_ANYTHING_REC_H+#define FAST_ANYTHING_REC_H+#include <stddef.h>+#ifdef __cplusplus+extern "C" {+#endif+extern int fa_rec_inside;+extern const int fa_rec_slices[10];+long long fa_rec_now(void);+void fa_rec_begin(void);+void fa_rec_i64(long long v);+void fa_rec_u64(unsigned long long v);+void fa_rec_f64(double v);+void fa_rec_bool(int v);+void fa_rec_str(const char *s);+void fa_rec_arr_i64(const void *p, size_t n, int size, int is_signed);+void fa_rec_arr_f64(const void *p, size_t n, int size);+/* kind: 'i' signed, 'u' unsigned, 'f' float, 'b' bool */+void fa_rec_done_i64(long long r, long long took);+void fa_rec_done_u64(unsigned long long r, long long took);+void fa_rec_done_f64(double r, long long took);+void fa_rec_done_bool(int r, long long took);+void fa_rec_derived_i64(long long r);+void fa_rec_derived_u64(unsigned long long r);+void fa_rec_derived_f64(double r);+void fa_rec_derived_bool(int r);+int fa_rec_derive_ok(void);+size_t fa_rec_rand(size_t below);+size_t fa_rec_chars(const char *s);+char *fa_rec_substr(const char *s, size_t off, size_t len);+void fa_rec_free(void *p);+#ifdef __cplusplus+}+#endif+#endifdiff --git a/src/cfamily/rec.hpp b/src/cfamily/rec.hppnew file mode 100644index 0000000..87d8fe4--- /dev/null+++ b/src/cfamily/rec.hpp@@ -0,0 +1,166 @@+// fast-anything recorder for C++ (C++14), force-included with -include for one run.+#ifndef FAST_ANYTHING_REC_HPP+#define FAST_ANYTHING_REC_HPP+#ifdef __cplusplus+#include <algorithm>+#include <array>+#include <chrono>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <map>+#include <string>+#include <tuple>+#include <type_traits>+#include <unordered_map>+#include <utility>+#include <vector>++namespace fa_rec {+/*JSON*/++struct State {+ bool inside = false;+ std::vector<std::string> kept, derived;+ long long calls = 0, skipped = 0, nanos = 0, derive_started = 0;+ size_t limit = 0;+ unsigned long long rng = 0xFA57;+};+inline State &st() { static State s; return s; }+inline long long now() {+ return (long long) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();+}+inline unsigned long long next() {+ auto &r = st().rng;+ r ^= r << 13;+ r ^= r >> 7;+ r ^= r << 17;+ return r;+}+inline void save() {+ auto &s = st();+ if (const char *path = std::getenv("FAST_ANYTHING_RECORD_OUT")) {+ if (FILE *f = std::fopen(path, "wb")) {+ for (auto &l : s.kept) std::fprintf(f, "%s\n", l.c_str());+ for (auto &l : s.derived) std::fprintf(f, "%s\n", l.c_str());+ std::fclose(f);+ }+ }+ if (const char *path = std::getenv("FAST_ANYTHING_RECORD_META")) {+ if (FILE *f = std::fopen(path, "wb")) {+ std::fprintf(f, "{\"calls\":%lld,\"kept\":%zu,\"skipped\":%lld,\"unsupported\":[%s],\"original_ns\":%.3f}", s.calls, s.kept.size(), s.skipped,+ s.skipped ? "\"a value JSON can't hold\"" : "", s.calls ? (double) s.nanos / (double) s.calls : 0.0);+ std::fclose(f);+ }+ }+}+inline bool ®istered() {+ static bool r = (std::atexit(save), true);+ return r;+}+inline bool derive_ok() {+ auto &s = st();+ const char *d = std::getenv("FAST_ANYTHING_RECORD_DERIVE");+ if (d && d[0] == '0') return false;+ if (!s.derive_started) s.derive_started = now();+ return s.derived.size() < 200 && now() - s.derive_started < 3000000000LL;+}++static const size_t SLICES[] = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55};+template <class T> std::vector<T> variants(const T &) { return {}; }+inline std::vector<std::string> variants(const std::string &v) {+ std::vector<size_t> starts;+ for (size_t i = 0; i < v.size(); i++)+ if (((unsigned char) v[i] & 0xC0) != 0x80) starts.push_back(i);+ std::vector<std::string> out;+ size_t n = starts.size();+ starts.push_back(v.size());+ if (n < 2) return out;+ for (size_t len : SLICES) {+ if (len >= n) break;+ for (int rep = 0; rep < (len < 2 ? 1 : 3); rep++) {+ size_t off = (size_t) (next() % (n - len + 1));+ out.push_back(v.substr(starts[off], starts[off + len] - starts[off]));+ }+ }+ return out;+}+template <class T, class Al> std::vector<std::vector<T, Al>> variants(const std::vector<T, Al> &v) {+ std::vector<std::vector<T, Al>> out;+ size_t n = v.size();+ if (n < 2) return out;+ for (size_t len : SLICES) {+ if (len >= n) break;+ for (int rep = 0; rep < (len < 2 ? 1 : 3); rep++) {+ size_t off = (size_t) (next() % (n - len + 1));+ out.emplace_back(v.begin() + off, v.begin() + off + len);+ }+ }+ return out;+}++template <class F, class Tup, size_t... I> auto apply(F &f, Tup &t, std::index_sequence<I...>) -> decltype(f(std::get<I>(t)...)) {+ return f(std::get<I>(t)...);+}+template <class Tup, size_t... I> bool encode_tuple(std::string &o, const Tup &t, std::index_sequence<I...>) { return enc_all(o, std::get<I>(t)...); }+template <size_t I, class F, class Tup, class Seq> void derive_one(F &f, const Tup &args, Seq seq) {+ for (auto &smaller : variants(std::get<I>(args))) {+ if (!derive_ok()) return;+ Tup next_args = args;+ std::get<I>(next_args) = smaller;+ std::string in = "[";+ if (!encode_tuple(in, next_args, seq)) continue;+ in += "]";+ try {+ auto r = apply(f, next_args, seq);+ std::string out;+ if (enc(out, r)) st().derived.push_back("{\"args\":" + in + ",\"result\":" + out + ",\"derived\":true}");+ } catch (...) {+ // outside the function's domain: not a fair test+ }+ }+}+template <class F, class Tup, size_t... I> void derive_all(F &f, const Tup &args, std::index_sequence<I...> seq) {+ int dummy[] = {0, (derive_one<I>(f, args, seq), 0)...};+ (void) dummy;+}++template <class F, class... A> auto call(F f, const A &...a) -> decltype(f(a...)) {+ auto &s = st();+ registered();+ s.inside = true;+ struct Reset {+ ~Reset() { st().inside = false; }+ } reset;+ if (!s.limit) {+ const char *l = std::getenv("FAST_ANYTHING_RECORD_LIMIT");+ s.limit = l && std::atoi(l) > 0 ? (size_t) std::atoi(l) : 500;+ }+ s.calls++;+ size_t slot = s.kept.size() < s.limit ? s.kept.size() : (size_t) (next() % (unsigned long long) s.calls);+ std::string in = "[";+ bool ok = slot < s.limit && enc_all(in, a...);+ in += "]";+ long long t = now();+ auto r = f(a...);+ s.nanos += now() - t;+ if (slot < s.limit) {+ std::string out;+ if (ok && enc(out, r)) {+ std::string line = "{\"args\":" + in + ",\"result\":" + out + "}";+ if (slot < s.kept.size()) s.kept[slot] = line;+ else s.kept.push_back(line);+ if (derive_ok()) {+ std::tuple<typename std::decay<A>::type...> args(a...);+ derive_all(f, args, std::index_sequence_for<A...>{});+ }+ } else {+ s.skipped++;+ }+ }+ return r;+}+} // namespace fa_rec+#endif+#endifdiff --git a/src/java.rs b/src/java.rsindex ba4580d..1cc4243 100644--- a/src/java.rs+++ b/src/java.rs@@ -25,11 +25,67 @@ const BRIDGE: &str = include_str!("java/Bridge.java");const VALUE_OPTS: &[&str] =&["-cp", "-classpath", "--class-path", "-p", "--module-path", "--add-modules", "--source", "--limit-modules"];+/// How the app is started: a source file, or a Maven or Gradle build.+#[derive(Debug, Clone, Copy, PartialEq)]+enum Runner {+ Source,+ Maven,+ Gradle,+}++fn runner(program: &str) -> Option<Runner> {+ match util::program_stem(program).trim_end_matches(".cmd").trim_end_matches(".bat") {+ "java" => Some(Runner::Source),+ "mvn" | "mvnw" | "mvnd" => Some(Runner::Maven),+ "gradle" | "gradlew" => Some(Runner::Gradle),+ _ => None,+ }+}+pub fn is_java(program: &str) -> bool {- util::program_stem(program) == "java"+ runner(program).is_some()+}++/// The program as given, or its .cmd / .bat twin on Windows (mvn, gradlew).+fn build_tool(program: &str, root: &Path) -> Result<String> {+ let base = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };+ let mut candidates = vec![base.clone()];+ if cfg!(windows) && base.extension().is_none() {+ candidates.insert(0, base.with_extension("cmd"));+ candidates.insert(1, base.with_extension("bat"));+ }+ for c in candidates {+ if let Ok(out) = Command::new(&c).arg("--version").current_dir(root).stdin(Stdio::null()).output()+ && out.status.success()+ {+ return Ok(c.to_string_lossy().into_owned());+ }+ }+ bail!("{program} didn't run: is it installed (or is the wrapper script in the project)?")+}++/// The JDK that runs the build: JAVA_HOME, else java on the PATH.+fn build_java(root: &Path) -> Result<String> {+ match std::env::var_os("JAVA_HOME").filter(|h| !h.is_empty()) {+ Some(home) => {+ let java = Path::new(&home).join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });+ resolve_java(&java.to_string_lossy(), root)+ }+ None => resolve_java("java", root),+ }}pub fn resolve(program: &str, root: &Path) -> Result<String> {+ match runner(program) {+ Some(Runner::Maven | Runner::Gradle) => {+ build_java(root)?;+ build_tool(program, root)+ }+ _ => resolve_java(program, root),+ }+}++fn resolve_java(program: &str, root: &Path) -> Result<String> {let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };let out = output(Command::new(&prog).args(["-XshowSettings:properties", "-version"]).current_dir(root), "java")?;let text = combined(&out);@@ -66,10 +122,37 @@ fn entry(args: &[String]) -> Result<&str> {}}-fn source_files(root: &Path, entry: &str) -> Vec<PathBuf> {- let start = root.join(entry).parent().map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf());+/// The app's sources: the folder of the source file, or every src/main/java of a build.+fn sources(root: &Path, program: &str, args: &[String]) -> Result<Vec<PathBuf>> {+ if runner(program) == Some(Runner::Source) {+ let entry = entry(args)?;+ return Ok(source_files(root.join(entry).parent().unwrap_or(root)));+ }+ let mut dirs = Vec::new();+ let mut stack = vec![root.to_path_buf()];+ while let Some(dir) = stack.pop() {+ let main = dir.join("src").join("main").join("java");+ if main.is_dir() {+ dirs.push(main);+ }+ let Ok(entries) = fs::read_dir(&dir) else { continue };+ for e in entries.flatten() {+ let name = e.file_name().to_string_lossy().into_owned();+ if e.path().is_dir()+ && !name.starts_with('.')+ && !["target", "build", "out", "node_modules", "src"].contains(&name.as_str())+ {+ stack.push(e.path());+ }+ }+ }+ ensure!(!dirs.is_empty(), "no src/main/java folder in this project");+ Ok(dirs.iter().flat_map(|d| source_files(d)).collect())+}++fn source_files(start: &Path) -> Vec<PathBuf> {let mut out = Vec::new();- let mut stack = vec![start];+ let mut stack = vec![start.to_path_buf()];while let Some(dir) = stack.pop() {let Ok(entries) = fs::read_dir(&dir) else { continue };for e in entries.flatten() {@@ -144,31 +227,64 @@ fn hotspot(ctx: &Ctx, m: &Method, total: f64, wall: f64, own: u64, incl: u64) ->}}-pub fn profile(ctx: &Ctx, java: &str, args: &[String]) -> Result<Profile> {- let entry = entry(args)?.to_string();- let jfr_file = ctx.fast.join("profile.jfr");- let _ = fs::remove_file(&jfr_file);+/// What bench times: Gradle runs without its daemon, which would otherwise outlive the run and+/// hold its output pipe open.+pub fn bench_command(ctx: &Ctx, program: &str) -> Result<(String, Vec<String>)> {+ let mut args = ctx.state.command[1..].to_vec();+ if runner(program) == Some(Runner::Gradle) && !args.iter().any(|a| a == "--no-daemon") {+ args.insert(0, "--no-daemon".into());+ }+ Ok((program.to_string(), args))+}++/// The app's command, ready to run: for Gradle without a lingering daemon.+fn app_command(program: &str, args: &[String]) -> Command {+ let mut cmd = Command::new(program);+ if runner(program) == Some(Runner::Gradle) {+ cmd.arg("--no-daemon");+ }+ cmd.args(args);+ cmd+}++pub fn profile(ctx: &Ctx, program: &str, args: &[String]) -> Result<Profile> {+ let build = runner(program) != Some(Runner::Source);+ let java = if build { build_java(&ctx.root)? } else { program.to_string() };+ let jfr_dir = ctx.fast.join("jfr");+ let _ = fs::remove_dir_all(&jfr_dir);+ fs::create_dir_all(&jfr_dir)?;+ let flags = format!(+ "-XX:StartFlightRecording:filename={}/%p.jfr,settings=profile -Xlog:jfr+startup=error",+ util::forward_slashes(&jfr_dir)+ );+ let mut cmd = if build { app_command(program, args) } else { Command::new(program) };+ if build {+ // every JVM the build starts (Maven's own, Gradle's forked app) records itself+ let existing = std::env::var("JAVA_TOOL_OPTIONS").unwrap_or_default();+ cmd.env("JAVA_TOOL_OPTIONS", format!("{existing} {flags}").trim());+ } else {+ cmd.args(flags.split(' ')).args(args);+ }let started = Instant::now();- let run = output(- Command::new(java)- .arg("-XX:StartFlightRecording:filename=.fast/profile.jfr,settings=profile")- .arg("-Xlog:jfr+startup=error")- .args(args)- .current_dir(&ctx.root)- .env(DISABLE_ENV, "1")- .stdin(Stdio::null()),- "java",- )?;+ let run = output(cmd.current_dir(&ctx.root).env(DISABLE_ENV, "1").stdin(Stdio::null()), program)?;let wall = started.elapsed().as_secs_f64();ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));- let printed = output(- Command::new(tool(java, "jfr")).args(["print", "--events", "jdk.ExecutionSample", "--json"]).arg(&jfr_file),- "jfr",- )?;- ensure!(printed.status.success(), "reading the flight recording failed:\n{}", tail(&combined(&printed), 10));- let recording: Value = serde_json::from_slice(&printed.stdout).context("parsing the flight recording")?;+ let mut events = Vec::new();+ for f in fs::read_dir(&jfr_dir)?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jfr")) {+ let printed = output(+ Command::new(tool(&java, "jfr")).args(["print", "--events", "jdk.ExecutionSample", "--json"]).arg(&f),+ "jfr",+ )?;+ ensure!(printed.status.success(), "reading the flight recording failed:\n{}", tail(&combined(&printed), 10));+ let recording: Value = serde_json::from_slice(&printed.stdout).context("parsing the flight recording")?;+ if let Some(list) = recording["recording"]["events"].as_array() {+ events.extend(list.iter().cloned());+ }+ }+ ensure!(!events.is_empty(), "no flight recording was written: did a JVM run the app?");+ let recording = serde_json::json!({ "recording": { "events": events } });- let methods = describe(ctx, java, &source_files(&ctx.root, &entry))?;+ let methods = describe(ctx, &java, &sources(&ctx.root, program, args)?)?;let mut by_name: HashMap<(String, String), Vec<usize>> = HashMap::new();for (i, m) in methods.iter().enumerate() {by_name.entry((m.class.clone(), m.name.clone())).or_default().push(i);@@ -268,7 +384,7 @@ fn record_prologue(hs: &Hotspot) -> String {)}-pub fn record(ctx: &Ctx, java: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {+pub fn record(ctx: &Ctx, program: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {let file = ctx.root.join(&hs.file);let text = fs::read_to_string(&file).with_context(|| format!("reading {}", hs.file))?;let rec = REC.replace("/*PACKAGE*/", &package_line(&text)).replace("/*ID*/", &hs.id).replace("/*JSON*/", JSON);@@ -284,15 +400,14 @@ pub fn record(ctx: &Ctx, java: &str, args: &[String], hs: &Hotspot, out: &Path,patches.write(&native::sibling(&file, "FastAnythingRec.java")?, &rec)?;patches.write(&file, &patched)?;let run = output(- Command::new(java)- .args(args)+ app_command(program, args).current_dir(&ctx.root).env("FAST_ANYTHING_RECORD_OUT", out).env("FAST_ANYTHING_RECORD_META", &meta).env("FAST_ANYTHING_RECORD_LIMIT", limit.to_string()).env(DISABLE_ENV, "1").stdin(Stdio::null()),- "java",+ program,);patches.restore()?;let run = run?;@@ -364,7 +479,42 @@ fn hotspot_of<'a>(ctx: &'a Ctx, port: &Port) -> Result<&'a Hotspot> {.with_context(|| format!("{} isn't in the last scan: scan again", port.id))}+/// The Java release a Maven or Gradle build compiles for, when it says.+fn declared_release(root: &Path) -> Option<u32> {+ let num = |s: &str| -> Option<u32> {+ let digits: String =+ s.trim_start_matches(|c: char| !c.is_ascii_digit()).chars().take_while(char::is_ascii_digit).collect();+ digits.parse().ok().map(|n: u32| if n == 1 { 8 } else { n })+ };+ let mut found = Vec::new();+ for name in ["pom.xml", "build.gradle", "build.gradle.kts"] {+ let Ok(text) = fs::read_to_string(root.join(name)) else { continue };+ for key in [+ "<maven.compiler.release>",+ "<release>",+ "<maven.compiler.source>",+ "<source>",+ "JavaLanguageVersion.of(",+ "VERSION_",+ "release =",+ "release.set(",+ ] {+ for (i, _) in text.match_indices(key) {+ if let Some(n) = num(&text[i + key.len()..(i + key.len() + 12).min(text.len())]) {+ found.push(n);+ }+ }+ }+ }+ found.into_iter().min()+}+pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {+ if let Some(release) = declared_release(&ctx.root).filter(|r| *r < 22) {+ bail!(+ "the build compiles for Java {release}; the Rust bridge uses the FFM API from Java 22. Raise the release to 22+ (or run the app as java App.java)"+ );+ }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))?;@@ -421,5 +571,20 @@ mod tests {);assert!(entry(&["-jar".into(), "app.jar".into()]).is_err());assert!(is_java("C:\\jdk\\bin\\java.exe") && !is_java("javac"));+ assert_eq!(runner("mvn"), Some(Runner::Maven));+ assert_eq!(runner("./gradlew"), Some(Runner::Gradle));+ assert_eq!(runner("gradlew.bat"), Some(Runner::Gradle));+ let dir = std::env::temp_dir().join("fa-release-test");+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(+ dir.join("pom.xml"),+ "<properties><maven.compiler.release>17</maven.compiler.release></properties>",+ )+ .unwrap();+ assert_eq!(declared_release(&dir), Some(17));+ std::fs::write(dir.join("pom.xml"), "<project/>").unwrap();+ std::fs::write(dir.join("build.gradle.kts"), "tasks.withType<JavaCompile> { options.release = 25 }").unwrap();+ assert_eq!(declared_release(&dir), Some(25));+ std::fs::remove_dir_all(&dir).unwrap();}}diff --git a/src/main.rs b/src/main.rsindex 5ced00d..2a9a5f3 100644--- a/src/main.rs+++ b/src/main.rs@@ -3,6 +3,7 @@mod agent;mod backend;mod bench;+mod cfamily;mod doctor;mod golang;mod hotspot;diff --git a/src/pipeline.rs b/src/pipeline.rsindex 7906783..df0e3bd 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -24,7 +24,7 @@ pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {"put the command that runs your app after --, e.g. fast-anything scan -- python app.py");let mut ctx = Ctx::open(root)?;- let lang = Lang::detect(&command[0])?;+ let lang = crate::cfamily::refine(Lang::detect(&command[0])?, &command[1..]);let exe = lang.resolve(&command[0], &ctx.root)?;ui::step(format!("profiling {}", ui::bold(command.join(" "))));let profile = lang.profile(&ctx, &exe, &command[1..])?;