Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

PHP support

EL4CTEO6b842b5b1e33
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 30ba53f..b29af46 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,6 +34,10 @@ jobs:
with:
distribution: temurin
java-version: "25"
+ - uses: shivammathur/setup-php@v2
+ with:
+ php-version: "8.4"
+ extensions: ffi
- uses: actions/setup-go@v7
with:
go-version: stable
@@ -111,3 +115,17 @@ jobs:
$fa disable
git diff --exit-code fuzzy.go main.go
test -z "$(git status --porcelain .)"
+ - name: end to end, PHP
+ working-directory: examples/fuzzy-dedupe-php
+ run: |
+ fa=../../target/release/fast-anything
+ $fa scan -- php app.php
+ $fa port
+ cp reference/port.rs .fast/ports/$(ls .fast/ports)/src/port.rs
+ $fa verify
+ $fa enable
+ php app.php
+ $fa bench --runs 2
+ $fa disable
+ git diff --exit-code fuzzy.php
+ test -z "$(git status --porcelain .)"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d207699..803c426 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## Unreleased
+
+- 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.
+
## 0.2.0
- Java (22+): apps run as `java App.java`. Profiled with Flight Recorder, parsed with javac's own parser, ports called through the FFM API.
diff --git a/README.md b/README.md
index e672120..6e99bcd 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@
<a href="https://www.npmjs.com/package/@el4cteo/fast-anything"><img src="https://img.shields.io/npm/v/@el4cteo/fast-anything?color=f74c00&label=npm" alt="npm"></a>
<a href="https://crates.io/crates/fast-anything"><img src="https://img.shields.io/crates/v/fast-anything?color=f74c00" alt="crates.io"></a>
<a href="https://github.com/EL4CTEO/fast-anything/actions/workflows/ci.yml"><img src="https://github.com/EL4CTEO/fast-anything/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
- <img src="https://img.shields.io/badge/Python%20%C2%B7%20Node%20%C2%B7%20TypeScript%20%C2%B7%20Ruby%20%C2%B7%20Java%20%C2%B7%20Go-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Go">
+ <img src="https://img.shields.io/badge/Python%20%C2%B7%20Node%20%C2%B7%20TypeScript%20%C2%B7%20Ruby%20%C2%B7%20Java%20%C2%B7%20Go%20%C2%B7%20PHP-2563eb" alt="Python, Node, TypeScript, Ruby, Java, Go, PHP">
<img src="https://img.shields.io/badge/Claude%20Code-plugin-d97757" alt="Claude Code plugin">
<img src="https://img.shields.io/badge/MCP-server-555" alt="MCP server">
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-555" alt="MIT"></a>
@@ -31,7 +31,7 @@ Ports are compiled with your Rust toolchain ([rustup](https://rustup.rs)).
## Use
```sh
-fast-anything go --agent claude -- python app.py # or: -- node app.ts / ruby app.rb / java App.java / go run .
+fast-anything go --agent claude -- python app.py # or: -- node app.ts / ruby app.rb / java App.java / go run . / php app.php
```
Or step by step:
@@ -62,6 +62,7 @@ Real runs on an i5-10500, Windows 11. Reproduce them from [`examples/`](examples
|---|---|---|
| Python fuzzy dedupe (700 names) | 4.91s | **42ms, 116×** |
| TypeScript fuzzy dedupe (2,000 names) | 3.11s | **155ms, 20×** |
+| PHP fuzzy dedupe (600 names) | 2.94s | **53ms, 55×** |
| Go fuzzy dedupe (3,000 names) | 3.02s | **144ms, 21×** |
| Ruby fuzzy dedupe (400 names) | 3.13s | **228ms, 14×** |
| Java fuzzy dedupe (4,000 names) | 3.50s | **1.18s, 3×** (11× on the function; the rest is JVM startup) |
@@ -89,11 +90,12 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| 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 | ✅ |
| Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo) | ✅ |
-| PHP, C, C++ | the same C bridge | next |
+| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ |
+| C, C++ | the same C bridge | next |
-It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Java that means static methods, in Go plain functions. `scan` says why anything else can't move yet.
+It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`). In Java and PHP that means static methods (and PHP functions), in Go plain functions. `scan` says why anything else can't move yet.
-Ruby, Java and Go need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.
+Ruby, Java, Go and PHP need no headers, bindings or extra tools: the port is a plain Rust library with one C entry point taking and returning JSON, and fast-anything replays the recorded calls against it directly. Any language that can call C can use that bridge.
## License
diff --git a/examples/fuzzy-dedupe-php/app.php b/examples/fuzzy-dedupe-php/app.php
new file mode 100644
index 0000000..a138b82
--- /dev/null
+++ b/examples/fuzzy-dedupe-php/app.php
@@ -0,0 +1,37 @@
+<?php
+// Find near-duplicate customer names, the slow way.
+// php app.php
+declare(strict_types=1);
+
+require __DIR__ . '/fuzzy.php';
+
+const FIRST = ['Maria', 'Giulia', 'Sofia', 'Luca', 'Marco', 'Matteo', 'José', 'Zoë', 'Łukasz', 'Aiko', 'Chen', 'Olga', 'Ahmed',
+ 'Fatima', 'Liam', 'Emma', 'Noah', 'Ava', 'Mateo', 'Ingrid'];
+const LAST = ['Rossi', 'Russo', 'Ferrari', 'Esposito', 'Bianchi', 'García', 'Müller', 'Nowak', 'Tanaka', 'Wang', 'Ivanova',
+ 'Haddad', 'Smith', 'Johnson', 'Brown', 'Silva', 'Kowalski', 'Novák', 'Dubois', 'Larsen'];
+
+function make_names(int $count, int $seed): array
+{
+ mt_srand($seed);
+ $names = [];
+ for ($k = 0; $k < $count; $k++) {
+ $chars = preg_split('//u', FIRST[mt_rand(0, 19)] . ' ' . LAST[mt_rand(0, 19)], -1, PREG_SPLIT_NO_EMPTY);
+ if (mt_rand() / mt_getrandmax() < 0.35) {
+ $chars[mt_rand(0, count($chars) - 1)] = 'aeiourstln'[mt_rand(0, 9)];
+ }
+ $names[] = implode('', $chars);
+ }
+ return $names;
+}
+
+$names = make_names(600, 7);
+$pairs = Fuzzy::findDuplicates($names);
+echo count($names), ' names, ', count($pairs), " likely duplicate pairs\n";
+$shown = 0;
+foreach ($pairs as [$i, $j]) {
+ if ($shown === 5) break;
+ if ($names[$i] !== $names[$j]) {
+ echo " {$names[$i]} ~ {$names[$j]}\n";
+ $shown++;
+ }
+}
diff --git a/examples/fuzzy-dedupe-php/fuzzy.php b/examples/fuzzy-dedupe-php/fuzzy.php
new file mode 100644
index 0000000..ce7adb4
--- /dev/null
+++ b/examples/fuzzy-dedupe-php/fuzzy.php
@@ -0,0 +1,46 @@
+<?php
+declare(strict_types=1);
+
+// Fuzzy string matching helpers.
+final class Fuzzy
+{
+ // Edit distance: how many inserts, deletes or substitutions turn a into b (by character).
+ public static function levenshtein(string $a, string $b): int
+ {
+ $a = preg_split('//u', $a, -1, PREG_SPLIT_NO_EMPTY);
+ $b = preg_split('//u', $b, -1, PREG_SPLIT_NO_EMPTY);
+ if (count($a) < count($b)) {
+ [$a, $b] = [$b, $a];
+ }
+ $previous = range(0, count($b));
+ foreach ($a as $i => $ca) {
+ $current = [$i + 1];
+ foreach ($b as $j => $cb) {
+ $current[] = min($previous[$j + 1] + 1, $current[$j] + 1, $previous[$j] + ($ca === $cb ? 0 : 1));
+ }
+ $previous = $current;
+ }
+ return $previous[count($b)];
+ }
+
+ public static function normalize(string $name): string
+ {
+ return implode(' ', preg_split('/\s+/', strtolower(trim($name)), -1, PREG_SPLIT_NO_EMPTY));
+ }
+
+ // Index pairs of names within $maxDistance edits of each other.
+ public static function findDuplicates(array $names, int $maxDistance = 2): array
+ {
+ $clean = array_map([self::class, 'normalize'], $names);
+ $pairs = [];
+ $n = count($clean);
+ for ($i = 0; $i < $n; $i++) {
+ for ($j = $i + 1; $j < $n; $j++) {
+ if (self::levenshtein($clean[$i], $clean[$j]) <= $maxDistance) {
+ $pairs[] = [$i, $j];
+ }
+ }
+ }
+ return $pairs;
+ }
+}
diff --git a/examples/fuzzy-dedupe-php/reference/port.rs b/examples/fuzzy-dedupe-php/reference/port.rs
new file mode 100644
index 0000000..f9db607
--- /dev/null
+++ b/examples/fuzzy-dedupe-php/reference/port.rs
@@ -0,0 +1,76 @@
+//! Reference port of Fuzzy::findDuplicates (with levenshtein and normalize inside it):
+//! what a good agent run produces. CI uses it to test the pipeline without an agent.
+#![allow(non_snake_case)]
+
+/// PHP's implode(' ', preg_split('/\s+/', strtolower(trim($name)), -1, PREG_SPLIT_NO_EMPTY)), as characters.
+/// strtolower only touches ASCII; \s without /u is ASCII whitespace.
+fn normalize(name: &str) -> Vec<char> {
+ let is_space = |c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C');
+ let trimmed = name.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\0' | '\x0B'));
+ let mut out = Vec::with_capacity(trimmed.len());
+ for word in trimmed.split(is_space).filter(|w| !w.is_empty()) {
+ if !out.is_empty() {
+ out.push(' ');
+ }
+ out.extend(word.chars().map(|c| c.to_ascii_lowercase()));
+ }
+ out
+}
+
+pub fn findDuplicates(names: Vec<String>, maxDistance: i64) -> Result<Vec<[i64; 2]>, String> {
+ if maxDistance < 0 {
+ return Ok(Vec::new());
+ }
+ let clean: Vec<Vec<char>> = names.iter().map(|n| normalize(n)).collect();
+ Ok(pairs(&clean, maxDistance as usize).into_iter().map(|(i, j)| [i as i64, j as i64]).collect())
+}
+
+/// Edit distance, one row on the shorter side, common prefix and suffix skipped.
+fn distance<T: PartialEq>(a: &[T], b: &[T], row: &mut Vec<usize>) -> usize {
+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[prefix..], &b[prefix..]);
+ let suffix = a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count();
+ let (a, b) = (&a[..a.len() - suffix], &b[..b.len() - suffix]);
+ let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
+ if short.is_empty() {
+ return long.len();
+ }
+ row.clear();
+ row.extend(0..=short.len());
+ for (i, ca) in long.iter().enumerate() {
+ let mut diagonal = row[0];
+ row[0] = i + 1;
+ for (j, cb) in short.iter().enumerate() {
+ let above = row[j + 1];
+ row[j + 1] = (above + 1).min(row[j] + 1).min(diagonal + usize::from(ca != cb));
+ diagonal = above;
+ }
+ }
+ row[short.len()]
+}
+
+/// All (i, j) with i < j and distance <= max, in the original loop order, spread over threads.
+fn pairs<T: PartialEq + Sync>(clean: &[Vec<T>], max: usize) -> Vec<(usize, usize)> {
+ let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(clean.len().max(1));
+ let mut found: Vec<(usize, usize)> = std::thread::scope(|s| {
+ let workers: Vec<_> = (0..threads)
+ .map(|t| {
+ s.spawn(move || {
+ let mut row = Vec::new();
+ let mut out = Vec::new();
+ for i in (t..clean.len()).step_by(threads) {
+ for j in i + 1..clean.len() {
+ if clean[i].len().abs_diff(clean[j].len()) <= max && distance(&clean[i], &clean[j], &mut row) <= max {
+ out.push((i, j));
+ }
+ }
+ }
+ out
+ })
+ })
+ .collect();
+ workers.into_iter().flat_map(|w| w.join().expect("worker panicked")).collect()
+ });
+ found.sort_unstable();
+ found
+}
diff --git a/src/backend.rs b/src/backend.rs
index ae04da6..873c41a 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, python, ruby};
+use crate::{golang, java, node, php, python, ruby};
use anyhow::{Context, Result, bail, ensure};
use serde::{Deserialize, Serialize};
use std::fs;
@@ -20,6 +20,7 @@ pub enum Lang {
Ruby,
Java,
Go,
+ Php,
}
#[derive(Deserialize)]
@@ -49,16 +50,18 @@ impl Lang {
Ok(Lang::Java)
} else if golang::is_go(program) {
Ok(Lang::Go)
+ } else if php::is_php(program) {
+ Ok(Lang::Php)
} else {
bail!(
- "fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java and Go. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run ."
+ "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"
)
}
}
/// 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)
+ matches!(self, Lang::Ruby | Lang::Java | Lang::Go | Lang::Php)
}
pub fn label(self) -> &'static str {
@@ -68,6 +71,7 @@ impl Lang {
Lang::Ruby => "Ruby",
Lang::Java => "Java",
Lang::Go => "Go",
+ Lang::Php => "PHP",
}
}
@@ -78,6 +82,7 @@ impl Lang {
Lang::Ruby => ruby::resolve(program, root),
Lang::Java => java::resolve(program, root),
Lang::Go => golang::resolve(program, root),
+ Lang::Php => php::resolve(program, root),
}
}
@@ -88,6 +93,7 @@ impl Lang {
Lang::Ruby => ruby::profile(ctx, exe, args),
Lang::Java => java::profile(ctx, exe, args),
Lang::Go => golang::profile(ctx, exe, args),
+ Lang::Php => php::profile(ctx, exe, args),
}
}
@@ -106,6 +112,7 @@ impl Lang {
Lang::Ruby => ruby::record(ctx, exe, args, hs, out, limit),
Lang::Java => java::record(ctx, exe, args, hs, out, limit),
Lang::Go => golang::record(ctx, exe, args, hs, out, limit),
+ Lang::Php => php::record(ctx, exe, args, hs, out, limit),
}
}
@@ -116,6 +123,7 @@ impl Lang {
Lang::Ruby => ruby::scaffold(ctx, hs, helpers, port),
Lang::Java => java::scaffold(ctx, hs, helpers, port),
Lang::Go => golang::scaffold(ctx, hs, helpers, port),
+ Lang::Php => php::scaffold(ctx, hs, helpers, port),
}
}
@@ -126,6 +134,7 @@ impl Lang {
Lang::Ruby => ruby::verify(ctx, port),
Lang::Java => java::verify(ctx, port),
Lang::Go => golang::verify(ctx, port),
+ Lang::Php => php::verify(ctx, port),
}
}
@@ -136,6 +145,7 @@ impl Lang {
Lang::Ruby => ruby::enable(ctx, port),
Lang::Java => java::enable(ctx, port),
Lang::Go => golang::enable(ctx, port),
+ Lang::Php => php::enable(ctx, port),
}
}
@@ -146,6 +156,7 @@ impl Lang {
Lang::Ruby => ruby::disable(ctx, port),
Lang::Java => java::disable(ctx, port),
Lang::Go => golang::disable(ctx, port),
+ Lang::Php => php::disable(ctx, port),
}
}
@@ -172,7 +183,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 => built.clone(),
+ Lang::Ruby | Lang::Java | Lang::Go | Lang::Php => built.clone(),
};
(built, dest)
}
diff --git a/src/doctor.rs b/src/doctor.rs
index 7de1914..6c1682e 100644
--- a/src/doctor.rs
+++ b/src/doctor.rs
@@ -47,6 +47,12 @@ pub fn run() -> Result<()> {
need: "for Go apps (1.22+)",
hint: "https://go.dev/dl",
},
+ Check {
+ name: "php",
+ found: version("php", &["--version"]),
+ need: "for PHP apps (8.1+, extension=ffi)",
+ hint: "https://php.net",
+ },
Check {
name: "claude",
found: version("claude", &["--version"]),
@@ -75,7 +81,7 @@ pub fn run() -> Result<()> {
}
}
ensure!(checks[0].found.is_some(), "Rust is needed to build ports");
- ensure!(checks[1..6].iter().any(|c| c.found.is_some()), "install Python, Node.js, Ruby, Java or Go");
+ ensure!(checks[1..7].iter().any(|c| c.found.is_some()), "install Python, Node.js, Ruby, Java, Go or PHP");
ui::ok("ready");
Ok(())
}
diff --git a/src/main.rs b/src/main.rs
index e9506bf..5ced00d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,6 +10,7 @@ mod java;
mod mcp;
mod native;
mod node;
+mod php;
mod pipeline;
mod python;
mod report;
diff --git a/src/native.rs b/src/native.rs
index 53b9f06..b069be2 100644
--- a/src/native.rs
+++ b/src/native.rs
@@ -397,6 +397,9 @@ pub fn same(a: &Value, b: &Value, loose_empty: bool) -> bool {
}
(Value::Null, Value::Array(v)) | (Value::Array(v), Value::Null) => loose_empty && v.is_empty(),
(Value::Null, Value::Object(v)) | (Value::Object(v), Value::Null) => loose_empty && v.is_empty(),
+ (Value::Array(a), Value::Object(o)) | (Value::Object(o), Value::Array(a)) => {
+ loose_empty && a.is_empty() && o.is_empty()
+ }
_ => a == b,
}
}
diff --git a/src/php.rs b/src/php.rs
new file mode 100644
index 0000000..4feccdb
--- /dev/null
+++ b/src/php.rs
@@ -0,0 +1,368 @@
+//! PHP backend: apps run as php app.php. Profiled by a one-line timer put into every function
+//! for one run, read with PHP's own tokenizer, and bridged with PHP's FFI extension.
+
+use crate::backend::{self, Profile, Recording};
+use crate::hotspot::{Hotspot, Param};
+use crate::native::{self, Flavor, Patches};
+use crate::python::DISABLE_ENV;
+use crate::state::{Ctx, Port, Verify};
+use crate::util::{self, combined, output, tail};
+use anyhow::{Context, Result, bail, ensure};
+use serde::Deserialize;
+use serde_json::Value;
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+
+const DESCRIBE: &str = include_str!("php/describe.php");
+const PROF: &str = include_str!("php/prof.php");
+const REC: &str = include_str!("php/rec.php");
+const BRIDGE: &str = include_str!("php/bridge.php");
+/// php options that take the next argument as their value.
+const VALUE_OPTS: &[&str] = &["-d", "-c", "-z"];
+
+pub fn is_php(program: &str) -> bool {
+ let stem = util::program_stem(program);
+ stem == "php" || (stem.starts_with("php") && stem[3..].chars().all(|c| c.is_ascii_digit() || c == '.'))
+}
+
+pub fn resolve(program: &str, root: &Path) -> Result<String> {
+ let prog = if program.contains(['/', '\\']) { root.join(program) } else { PathBuf::from(program) };
+ let out =
+ output(Command::new(&prog).args(["-r", "echo PHP_BINARY, PHP_EOL, PHP_VERSION;"]).current_dir(root), "php")?;
+ ensure!(out.status.success(), "{program} failed:\n{}", tail(&combined(&out), 5));
+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
+ let mut lines = text.lines();
+ let exe = lines.next().unwrap_or_default().trim().to_string();
+ let version: Vec<u32> = lines.next().unwrap_or_default().split('.').filter_map(|s| s.parse().ok()).collect();
+ ensure!(version.as_slice() >= &[8, 1][..], "PHP 8.1 or newer is needed (found {version:?})");
+ Ok(exe)
+}
+
+/// The script in php [options] app.php [args].
+fn entry(args: &[String]) -> Result<&str> {
+ let mut i = 0;
+ while i < args.len() && args[i].starts_with('-') {
+ if args[i] == "-f" {
+ return args.get(i + 1).map(String::as_str).context("-f needs a file");
+ }
+ i += if VALUE_OPTS.contains(&args[i].as_str()) { 2 } else { 1 };
+ }
+ args.get(i).map(String::as_str).filter(|f| f.ends_with(".php")).context("run the app as php app.php")
+}
+
+fn source_files(root: &Path, entry: &str) -> Vec<PathBuf> {
+ let start = root.join(entry).parent().map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf());
+ let mut out = Vec::new();
+ let mut stack = vec![start];
+ while let Some(dir) = stack.pop() {
+ let Ok(entries) = fs::read_dir(&dir) else { continue };
+ for e in entries.flatten() {
+ let p = e.path();
+ let name = e.file_name().to_string_lossy().into_owned();
+ if p.is_dir() {
+ if !name.starts_with('.') && !["vendor", "node_modules", "cache", "var"].contains(&name.as_str()) {
+ stack.push(p);
+ }
+ } else if name.ends_with(".php") {
+ out.push(p);
+ }
+ }
+ }
+ out
+}
+
+#[derive(Deserialize, Clone)]
+struct Func {
+ path: PathBuf,
+ name: String,
+ class: Option<String>,
+ qualname: String,
+ line: u32,
+ end_line: u32,
+ body_offset: usize,
+ params: Vec<Param>,
+ returns: Option<String>,
+ blockers: Vec<String>,
+ warnings: Vec<String>,
+ calls: Vec<String>,
+ source: String,
+}
+
+fn describe(ctx: &Ctx, php: &str, files: &[PathBuf]) -> Result<Vec<Func>> {
+ let script = ctx.fast.join("describe.php");
+ fs::write(&script, DESCRIBE)?;
+ let list = ctx.fast.join("php-files.txt");
+ fs::write(&list, files.iter().map(|f| f.to_string_lossy().into_owned()).collect::<Vec<_>>().join("\n"))?;
+ let out = ctx.fast.join("php-funcs.json");
+ let run =
+ output(Command::new(php).arg(&script).arg(&list).arg(&out).current_dir(&ctx.root).stdin(Stdio::null()), "php")?;
+ ensure!(run.status.success(), "reading the PHP sources failed:\n{}", tail(&combined(&run), 20));
+ serde_json::from_str(&fs::read_to_string(&out)?).context("reading the function list")
+}
+
+fn rel(ctx: &Ctx, p: &Path) -> String {
+ util::forward_slashes(p.strip_prefix(&ctx.root).unwrap_or(p))
+}
+
+fn hotspot(ctx: &Ctx, f: &Func, calls: u64, own: f64, cum: f64) -> Hotspot {
+ let file = rel(ctx, &f.path);
+ Hotspot {
+ module: Some(file.trim_end_matches(".php").replace('/', ".")),
+ file,
+ line: f.line,
+ end_line: f.end_line,
+ name: f.name.clone(),
+ qualname: f.qualname.clone(),
+ kind: "function".into(),
+ ncalls: calls,
+ tottime: own,
+ cumtime: cum,
+ portability: if f.blockers.is_empty() { 0.9 } else { 0.0 },
+ blockers: f.blockers.clone(),
+ warnings: f.warnings.clone(),
+ params: f.params.clone(),
+ returns: f.returns.clone(),
+ source: f.source.clone(),
+ calls: f.calls.clone(),
+ owner: f.class.clone(),
+ ..Hotspot::default()
+ }
+}
+
+/// Insert text right after the { of each function (same line: no line numbers move).
+fn insert_at(text: &str, mut at: Vec<(usize, String)>) -> String {
+ at.sort_by(|a, b| b.0.cmp(&a.0));
+ let mut out = text.to_string();
+ for (offset, piece) in at {
+ out.insert_str(offset, &piece);
+ }
+ out
+}
+
+fn run_php(
+ ctx: &Ctx,
+ php: &str,
+ prepend: &Path,
+ args: &[String],
+ env: &[(&str, &Path)],
+) -> Result<std::process::Output> {
+ let mut cmd = Command::new(php);
+ cmd.arg("-d")
+ .arg(format!("auto_prepend_file={}", prepend.display()))
+ .args(args)
+ .current_dir(&ctx.root)
+ .env(DISABLE_ENV, "1")
+ .stdin(Stdio::null());
+ for (k, v) in env {
+ cmd.env(k, v);
+ }
+ output(&mut cmd, "php")
+}
+
+pub fn profile(ctx: &Ctx, php: &str, args: &[String]) -> Result<Profile> {
+ let funcs = describe(ctx, php, &source_files(&ctx.root, entry(args)?))?;
+ let mut by_file: BTreeMap<&Path, Vec<(usize, String)>> = BTreeMap::new();
+ for (i, f) in funcs.iter().enumerate() {
+ if !f.blockers.iter().any(|b| b.contains("generator")) {
+ by_file
+ .entry(&f.path)
+ .or_default()
+ .push((f.body_offset, format!(" $__faP = new \\FastAnythingProf({i});")));
+ }
+ }
+ let prof = ctx.fast.join("prof.php");
+ fs::write(&prof, PROF)?;
+ let out = ctx.fast.join("profile.json");
+ let _ = fs::remove_file(&out);
+ 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 run = run_php(ctx, php, &prof, args, &[("FAST_ANYTHING_PROF_OUT", &out)]);
+ patches.restore()?;
+ let run = run?;
+ ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));
+ let result: Value = serde_json::from_str(&fs::read_to_string(&out).context("the profiler wrote nothing")?)?;
+ 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, f) in funcs.iter().enumerate() {
+ let helper =
+ funcs.iter().enumerate().any(|(j, g)| stat(j).is_some() && g.path == f.path && g.calls.contains(&f.name));
+ match stat(i) {
+ Some(s) => functions.push(hotspot(
+ ctx,
+ f,
+ s[0].as_u64().unwrap_or(0),
+ s[1].as_f64().unwrap_or(0.0),
+ s[2].as_f64().unwrap_or(0.0),
+ )),
+ None if helper => functions.push(hotspot(ctx, f, 0, 0.0, 0.0)),
+ None => {}
+ }
+ }
+ Ok(Profile { wall, base: ".".into(), functions })
+}
+
+fn name_const(hs: &Hotspot) -> &'static str {
+ if hs.owner.is_some() { "__METHOD__" } else { "__FUNCTION__" }
+}
+
+pub fn record(ctx: &Ctx, php: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
+ let file = ctx.root.join(&hs.file);
+ let funcs = describe(ctx, php, std::slice::from_ref(&file))?;
+ let f = funcs
+ .iter()
+ .filter(|f| f.qualname == hs.qualname)
+ .min_by_key(|f| (f.line as i64 - hs.line as i64).abs())
+ .with_context(|| format!("{} isn't in {} any more: scan again", hs.qualname, hs.file))?;
+ let call = if hs.owner.is_some() { format!("self::{}", hs.name) } else { hs.name.clone() };
+ let line = format!(
+ " if (!\\FastAnythingRec::$inside) return \\FastAnythingRec::record({}, func_get_args(), static fn(...$__faA) => {call}(...$__faA));",
+ name_const(hs)
+ );
+ let text = fs::read_to_string(&file)?;
+ let rec = ctx.fast.join("rec.php");
+ fs::write(&rec, REC)?;
+ let meta = out.with_extension("meta.json");
+ let _ = fs::remove_file(&meta);
+ let mut patches = Patches::new(ctx)?;
+ patches.write(&file, &insert_at(&text, vec![(f.body_offset, line)]))?;
+ let run = run_php(ctx, php, &rec, args, &[("FAST_ANYTHING_RECORD_OUT", out), ("FAST_ANYTHING_RECORD_META", &meta)]);
+ patches.restore()?;
+ let run = run?;
+ ensure!(run.status.success(), "the app failed while recording ({}):\n{}", run.status, tail(&combined(&run), 30));
+ let mut rec: Recording = serde_json::from_str(&fs::read_to_string(&meta).context("the recorder wrote nothing")?)?;
+ rec.kept = rec.kept.min(limit.max(rec.kept));
+ Ok(rec)
+}
+
+// ------------------------------------------------------------------ the crate
+
+/// Rust type for a PHP type declaration (arrays stay serde_json::Value: their shape is in the recordings).
+pub fn rust_type(t: &str) -> Option<String> {
+ let t = t.trim().to_ascii_lowercase();
+ if let Some(inner) = t.strip_prefix('?') {
+ return Some(format!("Option<{}>", rust_type(inner)?));
+ }
+ Some(match t.as_str() {
+ "int" => "i64".into(),
+ "float" => "f64".into(),
+ "string" => "String".into(),
+ "bool" => "bool".into(),
+ _ => return None,
+ })
+}
+
+/// A PHP default value as JSON, if it's a simple literal.
+pub fn default_json(value: &str) -> Option<String> {
+ let v = value.trim();
+ let lower = v.to_ascii_lowercase();
+ Some(match lower.as_str() {
+ "null" | "true" | "false" => lower,
+ "[]" | "array()" => "[]".into(),
+ _ if v.replace('_', "").parse::<i64>().is_ok() => v.replace('_', ""),
+ _ if v.parse::<f64>().is_ok() => v.into(),
+ _ if v.len() >= 2
+ && ((v.starts_with('"') && v.ends_with('"')) || (v.starts_with('\'') && v.ends_with('\''))) =>
+ {
+ serde_json::to_string(&v[1..v.len() - 1]).ok()?
+ }
+ _ => return None,
+ })
+}
+
+pub const FLAVOR: Flavor = Flavor {
+ lang: backend::Lang::Php,
+ fence: "php",
+ rust_type,
+ default_json,
+ rules: &[
+ "PHP strings are bytes: `strlen`, `substr` and `$s[$i]` work on bytes, `mb_*` functions on characters. Match what the original uses.",
+ "Lists arrive as JSON arrays, string-keyed arrays as JSON objects (keys in order). An empty array is `[]` either way.",
+ "PHP ints are `i64` and turn into floats on overflow; `/` gives a float unless the division is exact, `intdiv` truncates.",
+ "Untyped parameters arrive as `serde_json::Value`: pick concrete types from the recorded calls.",
+ ],
+};
+
+pub fn scaffold(ctx: &Ctx, hs: &Hotspot, helpers: &[Hotspot], port: &Port) -> Result<String> {
+ native::scaffold(ctx, hs, helpers, port, &FLAVOR)
+}
+
+pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
+ native::verify(ctx, port, true)
+}
+
+// ------------------------------------------------------------------ the bridge
+
+fn bridge_class(port: &Port) -> String {
+ format!("FastAnything_{}", util::slug(&port.id))
+}
+
+fn find_body(name: &str, hint: u32) -> impl Fn(&str) -> Option<usize> {
+ let header = format!("function {name}(");
+ let spaced = format!("function {name} (");
+ move |text: &str| native::body_line(text, hint, |l| l.contains(&header) || l.contains(&spaced))
+}
+
+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))?;
+ ensure!(
+ !text.trim_end().ends_with("?>"),
+ "{} ends with ?>: remove the closing tag so code can follow it",
+ port.file
+ );
+ if text.contains("namespace ")
+ && text.lines().any(|l| l.trim_start().starts_with("namespace ") && l.trim_end().ends_with('{'))
+ {
+ bail!("{} uses braced namespaces, which fast-anything can't add code to yet", port.file);
+ }
+ let class = bridge_class(port);
+ let from = file.parent().context("file has no folder")?;
+ let (_, lib) = port.lang.artifact(&port.ext);
+ let lib_rel = util::forward_slashes(&util::relative(from, &ctx.lib_dir().join(lib)));
+ let lib_lit = format!("'{}'", lib_rel.replace('\\', "\\\\").replace('\'', "\\'"));
+ let bridge = BRIDGE.replace("/*CLASS*/", &class).replace("/*ID*/", &port.id).replace("/*LIB*/", &lib_lit);
+ let prologue =
+ format!("if ({class}::$on ?? {class}::load()) return {class}::call({}, func_get_args());", name_const(hs));
+ let patched =
+ native::insert_in_body(&text, "//", &port.id, &prologue, find_body(&port.func, port.line.max(hs.line)))?;
+ 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 php_bits() {
+ assert!(is_php("php") && is_php("php8.3") && is_php("C:\\php\\php.exe") && !is_php("phpunit"));
+ let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
+ assert_eq!(entry(&s(&["-d", "memory_limit=1G", "app.php", "x"])).unwrap(), "app.php");
+ assert_eq!(default_json("0.85").as_deref(), Some("0.85"));
+ assert_eq!(default_json("NULL").as_deref(), Some("null"));
+ assert_eq!(default_json("array()").as_deref(), Some("[]"));
+ assert_eq!(rust_type("?int").as_deref(), Some("Option<i64>"));
+ assert_eq!(insert_at("function f() {\n}", vec![(14, " X;".into())]), "function f() { X;\n}");
+ }
+}
diff --git a/src/php/bridge.php b/src/php/bridge.php
new file mode 100644
index 0000000..514bee3
--- /dev/null
+++ b/src/php/bridge.php
@@ -0,0 +1,35 @@
+final class /*CLASS*/
+{
+ // Calls the verified Rust port of /*ID*/ through PHP's FFI extension (extension=ffi in php.ini).
+ // FAST_ANYTHING_DISABLE=1, or no FFI, runs the PHP version instead.
+ public static ?bool $on = null;
+ private static $ffi = null;
+ private static array $params = [];
+
+ public static function load(): bool
+ {
+ self::$on = false;
+ if (getenv('FAST_ANYTHING_DISABLE') !== false || !extension_loaded('ffi')) return false;
+ try {
+ self::$ffi = \FFI::cdef('uint8_t *fa_call(const char *input, size_t len, size_t *out_len); void fa_free(uint8_t *ptr, size_t len);', __DIR__ . '/' . /*LIB*/);
+ } catch (\Throwable $e) {
+ return false;
+ }
+ return self::$on = true;
+ }
+
+ public static function call(string $name, array $args)
+ {
+ $ps = self::$params[$name] ??= (str_contains($name, '::') ? new \ReflectionMethod(...explode('::', $name, 2)) : new \ReflectionFunction($name))->getParameters();
+ for ($i = count($args); $i < count($ps) && $ps[$i]->isDefaultValueAvailable(); $i++) $args[] = $ps[$i]->getDefaultValue();
+ $in = json_encode($args, JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
+ $len = self::$ffi->new('size_t');
+ $out = self::$ffi->fa_call($in, strlen($in), \FFI::addr($len));
+ $n = $len->cdata;
+ $text = \FFI::string($out, $n);
+ self::$ffi->fa_free($out, $n);
+ $reply = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
+ if (array_key_exists('error', $reply)) throw new \RuntimeException('fast-anything: ' . $reply['error']);
+ return $reply['ok'];
+ }
+}
\ No newline at end of file
diff --git a/src/php/describe.php b/src/php/describe.php
new file mode 100644
index 0000000..7e37aa5
--- /dev/null
+++ b/src/php/describe.php
@@ -0,0 +1,189 @@
+<?php
+// PHP side of fast-anything's scan: reads the app's files with PHP's own tokenizer and describes
+// every function and static method. The CLI runs it as php describe.php <file list> <out.json>.
+declare(strict_types=1);
+
+const IO = ['printf', 'vprintf', 'print_r', 'var_dump', 'var_export', 'fopen', 'fwrite', 'fputs', 'fread', 'fgets', 'fgetcsv',
+ 'fputcsv', 'file_get_contents', 'file_put_contents', 'file', 'readline', 'fscanf', 'unlink', 'mkdir', 'rmdir', 'header',
+ 'setcookie', 'exec', 'shell_exec', 'system', 'passthru', 'proc_open', 'popen', 'sleep', 'usleep', 'error_log', 'mail',
+ 'curl_exec', 'fsockopen', 'ob_start', 'flush', 'session_start', 'opendir', 'scandir', 'glob', 'touch', 'rename', 'copy',
+ 'tempnam', 'ini_set', 'set_time_limit', 'putenv', 'getenv', 'fclose', 'readfile', 'stream_get_contents', 'trigger_error'];
+const NONDET = ['rand', 'mt_rand', 'random_int', 'random_bytes', 'uniqid', 'time', 'microtime', 'hrtime', 'date', 'gmdate',
+ 'mktime', 'strtotime', 'shuffle', 'str_shuffle', 'array_rand', 'lcg_value', 'mt_srand', 'srand', 'getmypid'];
+const SCALARS = ['int', 'float', 'string', 'bool', 'array', 'mixed', 'null', '?int', '?float', '?string', '?bool', '?array',
+ 'int|float', 'float|int', 'iterable', 'false', 'true'];
+const SKIP = [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT];
+
+function text($t): string { return is_array($t) ? $t[1] : $t; }
+function id($t): ?int { return is_array($t) ? $t[0] : null; }
+
+function describe_file(string $path): array {
+ $src = file_get_contents($path);
+ $tokens = token_get_all($src);
+ $n = count($tokens);
+ $off = [];
+ $pos = 0;
+ foreach ($tokens as $i => $t) { $off[$i] = $pos; $pos += strlen(text($t)); }
+ $line = fn(int $byte): int => substr_count($src, "\n", 0, $byte) + 1;
+ $next = function (int $i) use ($tokens, $n): int { for ($i++; $i < $n && in_array(id($tokens[$i]), SKIP, true); $i++); return $i; };
+ $prev = function (int $i) use ($tokens): int { for ($i--; $i >= 0 && in_array(id($tokens[$i]), SKIP, true); $i--); return $i; };
+ $match = function (int $i, string $open, string $close) use ($tokens, $n): int {
+ $depth = 0;
+ for (; $i < $n; $i++) {
+ $t = $tokens[$i];
+ if ($t === $open || ($open === '{' && in_array(id($t), [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true))) $depth++;
+ elseif ($t === $close && --$depth === 0) return $i;
+ }
+ return $n - 1;
+ };
+
+ // top-level function names and static methods per class, for helper detection
+ $out = [];
+ $classes = []; // stack of [name, depth]
+ $depth = 0;
+ $funcs = [];
+ $statics = [];
+ $found = [];
+ for ($i = 0; $i < $n; $i++) {
+ $t = $tokens[$i];
+ if ($t === '{' || in_array(id($t), [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true)) { $depth++; continue; }
+ if ($t === '}') { $depth--; if ($classes && end($classes)[1] === $depth) array_pop($classes); continue; }
+ $k = id($t);
+ if (in_array($k, [T_CLASS, T_TRAIT, T_INTERFACE, T_ENUM], true)) {
+ $p = $prev($i);
+ if ($p >= 0 && (id($tokens[$p]) === T_DOUBLE_COLON || id($tokens[$p]) === T_NEW)) continue;
+ $nameAt = $next($i);
+ $classes[] = [text($tokens[$nameAt]), $depth];
+ continue;
+ }
+ if ($k !== T_FUNCTION) continue;
+ $j = $next($i);
+ $byRef = false;
+ if ($tokens[$j] === '&') { $byRef = true; $j = $next($j); }
+ if (id($tokens[$j]) !== T_STRING) continue; // a closure
+ $name = $tokens[$j][1];
+ $class = null;
+ if ($classes && $depth === end($classes)[1] + 1) $class = end($classes)[0];
+ elseif ($depth !== 0) continue; // declared inside a function body
+ // modifiers and the first token of the declaration
+ $start = $i;
+ $static = false;
+ for ($p = $prev($i); $p >= 0 && in_array(id($tokens[$p]), [T_STATIC, T_PUBLIC, T_PRIVATE, T_PROTECTED, T_FINAL, T_ABSTRACT], true); $p = $prev($p)) {
+ if (id($tokens[$p]) === T_STATIC) $static = true;
+ $start = $p;
+ }
+ $open = $next($j);
+ $close = $match($open, '(', ')');
+ $k2 = $next($close);
+ $returns = null;
+ if ($tokens[$k2] === ':') {
+ $r = '';
+ for ($k2 = $next($k2); $k2 < $n && $tokens[$k2] !== '{' && $tokens[$k2] !== ';'; $k2++) $r .= text($tokens[$k2]);
+ $returns = trim($r);
+ }
+ if ($tokens[$k2] !== '{') continue; // abstract or interface method
+ $bodyEnd = $match($k2, '{', '}');
+ $found[] = compact('name', 'class', 'static', 'byRef', 'start', 'open', 'close', 'returns', 'k2', 'bodyEnd');
+ if ($class === null) $funcs[strtolower($name)] = true;
+ elseif ($static) $statics[$class][strtolower($name)] = true;
+ }
+
+ foreach ($found as $f) {
+ ['name' => $name, 'class' => $class, 'static' => $static, 'byRef' => $byRef, 'start' => $start, 'open' => $open,
+ 'close' => $close, 'returns' => $returns, 'k2' => $brace, 'bodyEnd' => $bodyEnd] = $f;
+ $blockers = [];
+ $warnings = [];
+ if ($class !== null && !$static) $blockers[] = 'instance method (static methods and functions only for now)';
+ if ($byRef) $blockers[] = 'returns by reference';
+ // parameters
+ $params = [];
+ $cur = [];
+ $depthP = 0;
+ $flush = function () use (&$cur, &$params, &$blockers) {
+ if (!$cur) return;
+ $type = '';
+ $var = null;
+ $default = null;
+ $afterEq = false;
+ foreach ($cur as $t) {
+ if (in_array(id($t), SKIP, true) && !$afterEq) continue;
+ if ($afterEq) { $default .= text($t); continue; }
+ if ($t === '=') { $afterEq = true; $default = ''; continue; }
+ if ($t === '&') { $blockers[] = 'takes arguments by reference'; continue; }
+ if (id($t) === T_ELLIPSIS) { $blockers[] = 'takes variadic arguments'; continue; }
+ if (in_array(id($t), [T_PUBLIC, T_PRIVATE, T_PROTECTED, T_READONLY], true)) continue;
+ if (id($t) === T_VARIABLE) { $var = substr($t[1], 1); continue; }
+ $type .= text($t);
+ }
+ $type = trim($type);
+ if ($type !== '' && !in_array(strtolower($type), SCALARS, true)) $blockers[] = "takes a $type";
+ $params[] = ['name' => $var, 'annotation' => $type === '' ? null : $type, 'default' => $default === null ? null : trim($default)];
+ $cur = [];
+ };
+ for ($k = $open + 1; $k < $close; $k++) {
+ $t = $tokens[$k];
+ if ($t === '(' || $t === '[') $depthP++;
+ if ($t === ')' || $t === ']') $depthP--;
+ if ($t === ',' && $depthP === 0) { $flush(); continue; }
+ $cur[] = $t;
+ }
+ $flush();
+ if ($returns !== null) {
+ $rl = strtolower($returns);
+ if ($rl === 'void' || $rl === 'never') $blockers[] = "returns nothing ($returns)";
+ elseif (!in_array($rl, SCALARS, true)) $blockers[] = "returns a $returns";
+ }
+ if ($params && array_filter($params, fn($p) => $p['annotation'] === null)) $warnings[] = 'untyped parameters: types are inferred from recorded calls';
+ // the body
+ $io = [];
+ $nondet = [];
+ $helpers = [];
+ for ($k = $brace + 1; $k < $bodyEnd; $k++) {
+ $t = $tokens[$k];
+ $tk = id($t);
+ if (in_array($tk, [T_ECHO, T_PRINT, T_EXIT, T_INCLUDE, T_INCLUDE_ONCE, T_REQUIRE, T_REQUIRE_ONCE, T_EVAL, T_INLINE_HTML], true)) $io[] = strtolower(trim(text($t)));
+ if ($tk === T_GLOBAL || ($tk === T_VARIABLE && $t[1] === '$GLOBALS')) $blockers[] = 'uses global variables';
+ if ($tk === T_STATIC && id($tokens[$next($k)]) === T_VARIABLE) $blockers[] = 'keeps static variables';
+ if ($tk === T_VARIABLE && $t[1] === '$this') $blockers[] = 'uses $this';
+ if ($tk === T_YIELD || $tk === T_YIELD_FROM) $blockers[] = 'is a generator';
+ if (($tk === T_STRING || $tk === T_NAME_FULLY_QUALIFIED) && $tokens[$next($k)] === '(') {
+ $p = $tokens[$prev($k)];
+ $called = strtolower(ltrim($t[1], '\\'));
+ if (in_array(id($p), [T_OBJECT_OPERATOR, T_NULLSAFE_OBJECT_OPERATOR, T_FUNCTION, T_NEW], true)) continue;
+ if (id($p) === T_DOUBLE_COLON) {
+ $owner = strtolower(text($tokens[$prev($prev($k))]));
+ if ($class !== null && in_array($owner, ['self', 'static', strtolower($class)], true) && isset($statics[$class][$called]) && $called !== strtolower($name)) $helpers[] = $t[1];
+ continue;
+ }
+ if (in_array($called, IO, true) || str_starts_with($called, 'curl_') || str_starts_with($called, 'mysqli_') || str_starts_with($called, 'pg_')) $io[] = $called;
+ if (in_array($called, NONDET, true)) $nondet[] = $called;
+ if ($class === null && isset($funcs[$called]) && $called !== strtolower($name)) $helpers[] = $t[1];
+ }
+ }
+ if ($io) $blockers[] = 'does I/O: ' . implode(', ', array_slice(array_values(array_unique($io)), 0, 3));
+ if ($nondet) $blockers[] = 'not deterministic: ' . implode(', ', array_slice(array_values(array_unique($nondet)), 0, 3));
+ $helpers = array_values(array_unique($helpers));
+ if ($helpers) $warnings[] = 'calls ' . implode(', ', array_slice($helpers, 0, 3)) . ', they get ported together with it';
+ $braceByte = $off[$brace];
+ $lineEnd = strpos($src, "\n", $braceByte);
+ $rest = trim(substr($src, $braceByte + 1, ($lineEnd === false ? strlen($src) : $lineEnd) - $braceByte - 1));
+ if ($rest !== '' && !str_starts_with($rest, '//') && !str_starts_with($rest, '#')) $blockers[] = "its { doesn't end a line";
+ $startByte = $off[$start];
+ $endByte = $off[$bodyEnd] + 1;
+ $out[] = [
+ 'path' => $path, 'name' => $name, 'class' => $class, 'static' => $static,
+ 'qualname' => $class === null ? $name : "$class.$name",
+ 'line' => $line($startByte), 'end_line' => $line($endByte - 1), 'body_offset' => $braceByte + 1,
+ 'params' => $params, 'returns' => $returns, 'blockers' => array_values(array_unique($blockers)),
+ 'warnings' => $warnings, 'calls' => $helpers,
+ 'source' => str_replace("\r", '', substr($src, $startByte, $endByte - $startByte)),
+ ];
+ }
+ return $out;
+}
+
+$all = [];
+foreach (file($argv[1], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $path) {
+ try { array_push($all, ...describe_file($path)); } catch (Throwable $e) { /* unparsable: skip */ }
+}
+file_put_contents($argv[2], json_encode($all, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
diff --git a/src/php/prof.php b/src/php/prof.php
new file mode 100644
index 0000000..2bbde1b
--- /dev/null
+++ b/src/php/prof.php
@@ -0,0 +1,38 @@
+<?php
+// fast-anything's PHP profiler, prepended with -d auto_prepend_file for one run. Every function
+// in the project got one line, $__faP = new \FastAnythingProf(N); timed until the function returns.
+final class FastAnythingProf
+{
+ public static array $stats = [];
+ public static array $stack = [];
+ public static array $active = [];
+ public static int $started = 0;
+ private int $t;
+
+ public function __construct(private int $id)
+ {
+ self::$active[$id] = (self::$active[$id] ?? 0) + 1;
+ self::$stack[] = 0;
+ $this->t = hrtime(true);
+ }
+
+ public function __destruct()
+ {
+ $took = hrtime(true) - $this->t;
+ $children = array_pop(self::$stack) ?? 0;
+ $s = self::$stats[$this->id] ?? [0, 0, 0];
+ $s[0]++;
+ $s[1] += $took - $children;
+ if (--self::$active[$this->id] === 0) $s[2] += $took;
+ self::$stats[$this->id] = $s;
+ if (self::$stack) self::$stack[array_key_last(self::$stack)] += $took;
+ }
+}
+
+FastAnythingProf::$started = hrtime(true);
+register_shutdown_function(function () {
+ $wall = (hrtime(true) - FastAnythingProf::$started) / 1e9;
+ $stats = [];
+ foreach (FastAnythingProf::$stats as $id => [$calls, $own, $cum]) $stats[(string) $id] = [$calls, $own / 1e9, $cum / 1e9];
+ file_put_contents(getenv('FAST_ANYTHING_PROF_OUT'), json_encode(['wall' => $wall, 'stats' => (object) $stats]));
+});
diff --git a/src/php/rec.php b/src/php/rec.php
new file mode 100644
index 0000000..dfd50c7
--- /dev/null
+++ b/src/php/rec.php
@@ -0,0 +1,140 @@
+<?php
+// fast-anything's PHP recorder, prepended with -d auto_prepend_file for one run.
+final class FastAnythingRec
+{
+ public static bool $inside = false;
+ private static array $kept = [];
+ private static array $args = [];
+ private static int $calls = 0;
+ private static int $skipped = 0;
+ private static int $nanos = 0;
+ private static array $why = [];
+ private static $fn = null;
+ private static array $params = [];
+
+ /** Missing optional arguments, filled in from the declaration like PHP does. */
+ public static function full(string $name, array $args): array
+ {
+ $ps = self::$params[$name] ??= (str_contains($name, '::') ? new ReflectionMethod(...explode('::', $name, 2)) : new ReflectionFunction($name))->getParameters();
+ for ($i = count($args); $i < count($ps); $i++) {
+ if (!$ps[$i]->isDefaultValueAvailable()) break;
+ $args[] = $ps[$i]->getDefaultValue();
+ }
+ return $args;
+ }
+
+ public static function enc($v): string
+ {
+ self::check($v);
+ return json_encode($v, JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
+ }
+
+ private static function check($v): void
+ {
+ if (is_array($v)) { foreach ($v as $x) self::check($x); return; }
+ if (is_float($v) && !is_finite($v)) throw new InvalidArgumentException('NaN or INF');
+ if (is_string($v) && !preg_match('//u', $v)) throw new InvalidArgumentException('binary string');
+ if (is_object($v)) throw new InvalidArgumentException(get_class($v) . ' object');
+ if (is_resource($v)) throw new InvalidArgumentException('resource');
+ }
+
+ public static function record(string $name, array $args, callable $fn)
+ {
+ $args = self::full($name, $args);
+ self::$fn = $fn;
+ self::$inside = true;
+ try {
+ self::$calls++;
+ $limit = (int) (getenv('FAST_ANYTHING_RECORD_LIMIT') ?: 500);
+ $slot = count(self::$kept) < $limit ? count(self::$kept) : random_int(0, self::$calls - 1);
+ $enc = null;
+ if ($slot < $limit) {
+ try { $enc = self::enc($args); } catch (Throwable $e) { self::$skipped++; self::$why[$e->getMessage()] = true; }
+ }
+ $t = hrtime(true);
+ try {
+ $r = $fn(...$args);
+ } catch (Throwable $e) {
+ self::$nanos += hrtime(true) - $t;
+ if ($enc !== null) self::store($slot, '{"args":' . $enc . ',"raises":' . json_encode(get_class($e)) . '}', null);
+ throw $e;
+ }
+ self::$nanos += hrtime(true) - $t;
+ if ($enc !== null) {
+ try { self::store($slot, '{"args":' . $enc . ',"result":' . self::enc($r) . '}', $args); }
+ catch (Throwable $e) { self::$skipped++; self::$why[$e->getMessage()] = true; }
+ }
+ return $r;
+ } finally {
+ self::$inside = false;
+ }
+ }
+
+ private static function store(int $slot, string $line, ?array $args): void
+ {
+ self::$kept[$slot] = $line;
+ self::$args[$slot] = $args;
+ }
+
+ private static function variants($v): array
+ {
+ $out = [];
+ if (is_string($v)) {
+ $chars = preg_split('//u', $v, -1, PREG_SPLIT_NO_EMPTY);
+ if ($chars === false) return [];
+ } elseif (is_array($v) && array_is_list($v)) {
+ $chars = $v;
+ } else {
+ return [];
+ }
+ $n = count($chars);
+ if ($n < 2) return [];
+ mt_srand(0xFA57);
+ foreach ([0, 1, 2, 3, 5, 8, 13, 21, 34, 55] as $len) {
+ if ($len >= $n) break;
+ for ($rep = 0; $rep < ($len < 2 ? 1 : 3); $rep++) {
+ $slice = array_slice($chars, mt_rand(0, $n - $len), $len);
+ $out[] = is_string($v) ? implode('', $slice) : $slice;
+ }
+ }
+ return $out;
+ }
+
+ public static function save(): void
+ {
+ self::$inside = true;
+ $derived = [];
+ $seen = [];
+ $start = hrtime(true);
+ if (self::$fn !== null) {
+ foreach (self::$args as $args) {
+ if ($args === null) continue;
+ foreach ($args as $i => $arg) {
+ foreach (self::variants($arg) as $smaller) {
+ if (count($derived) >= 200 || hrtime(true) - $start > 3e9) break 3;
+ $next = $args;
+ $next[$i] = $smaller;
+ try {
+ $enc = self::enc($next);
+ if (isset($seen[$enc])) continue;
+ $seen[$enc] = true;
+ $r = (self::$fn)(...$next);
+ $derived[] = '{"args":' . $enc . ',"result":' . self::enc($r) . ',"derived":true}';
+ } catch (Throwable $e) {
+ // outside the function's domain: not a fair test
+ }
+ }
+ }
+ }
+ }
+ ksort(self::$kept);
+ $lines = array_merge(array_values(self::$kept), $derived);
+ file_put_contents(getenv('FAST_ANYTHING_RECORD_OUT'), $lines ? implode("\n", $lines) . "\n" : '');
+ file_put_contents(getenv('FAST_ANYTHING_RECORD_META'), json_encode([
+ 'calls' => self::$calls, 'kept' => count(self::$kept), 'skipped' => self::$skipped,
+ 'unsupported' => array_keys(self::$why), 'original_ns' => self::$calls ? self::$nanos / self::$calls : 0,
+ ]));
+ }
+}
+
+register_shutdown_function([FastAnythingRec::class, 'save']);