use std::fmt::Write as _;
use crate::bridge::Manifest;
use crate::ts::exports::ExportedFn;
const CODEC_PHP: &str = r#"namespace RustAnything {
if (!\class_exists(Codec::class, false)) {
final class Codec
{
public const FLAGS = \JSON_PRESERVE_ZERO_FRACTION | \JSON_THROW_ON_ERROR
| \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE;
public const DEPTH = 100000;
public static function enc($v)
{
if (\is_float($v)) {
if (\is_nan($v)) {
return ['$num' => 'NaN'];
}
if (\is_infinite($v)) {
return ['$num' => $v > 0 ? 'Infinity' : '-Infinity'];
}
if ($v == 0.0 && \fdiv(1.0, $v) < 0) {
return ['$num' => '-0'];
}
return $v;
}
if (\is_array($v)) {
$out = [];
foreach ($v as $k => $x) {
$out[$k] = self::enc($x);
}
return $out;
}
if (\is_object($v)) {
return ['$object' => \get_class($v)];
}
if (\is_resource($v)) {
return ['$resource' => \get_resource_type($v)];
}
return $v;
}
public static function dec($v)
{
if (!\is_array($v)) {
return $v;
}
if (\count($v) === 1 && \array_key_exists('$num', $v)) {
return ['NaN' => \NAN, 'Infinity' => \INF, '-Infinity' => -\INF, '-0' => -0.0][$v['$num']];
}
if (\count($v) === 1 && \array_key_exists('$undefined', $v)) {
return null;
}
$out = [];
foreach ($v as $k => $x) {
$out[$k] = self::dec($x);
}
return $out;
}
public static function json($v): string
{
return \json_encode(self::enc($v), self::FLAGS);
}
public static function error(string $message): \Throwable
{
if (\preg_match('/^\\\\?([A-Za-z_][A-Za-z0-9_]*(?:\\\\[A-Za-z_][A-Za-z0-9_]*)*): (.*)$/s', $message, $m)
&& \class_exists($m[1])
&& \is_subclass_of($m[1], \Throwable::class)
) {
try {
return new $m[1]($m[2]);
} catch (\Throwable $e) {
}
}
return new \RuntimeException($message);
}
}
}
}
"#;
pub fn wrapper_path(m: &Manifest) -> String {
format!("php/{}.php", m.lib_name())
}
fn library_names(m: &Manifest) -> (String, String, String) {
let lib = m.lib_name();
(
format!("lib{lib}.dylib"),
format!("{lib}.dll"),
format!("lib{lib}.so"),
)
}
pub fn native_class(m: &Manifest) -> String {
format!("Native{}", crate::codegen_ruby::camel(&m.lib_name()))
}
pub fn qualified(f: &ExportedFn) -> (String, String) {
let proto = f.prototype.as_deref().unwrap_or(&f.name);
let head = proto.split('(').next().unwrap_or(proto).trim();
match head.rsplit_once('\\') {
Some((ns, _)) => (ns.to_string(), head.to_string()),
None => (String::new(), head.to_string()),
}
}
fn signature(f: &ExportedFn) -> String {
crate::lang::ruby::signature(f)
}
pub fn wrapper(m: &Manifest) -> String {
let (dylib, dll, so) = library_names(m);
let class = native_class(m);
let mut out = format!(
"<?php\n\n\
// The Rust port of `{unit}`, generated by rust-anything: the same functions, each calling the\n\
// Rust library through PHP's FFI extension. Require it in place of the original files.\n\
// Regenerate with `rust-anything refresh`.\n\n\
{CODEC_PHP}\n\
namespace RustAnything {{\n \
final class {class}\n {{\n \
private static $ffi = null;\n\n \
public static function call(string $name, array $args)\n {{\n \
if (self::$ffi === null) {{\n \
$lib = \\PHP_OS_FAMILY === 'Darwin' ? '{dylib}' : (\\PHP_OS_FAMILY === 'Windows' ? '{dll}' : '{so}');\n \
self::$ffi = \\FFI::cdef(\n \
'char *rust_anything_call(const char *name, const char *args); void rust_anything_free(char *ptr);',\n \
__DIR__ . '/' . $lib\n );\n }}\n \
$ptr = self::$ffi->rust_anything_call($name, Codec::json($args));\n \
if ($ptr === null) {{\n \
throw new \\RuntimeException(\"rust-anything: no answer from `$name`\");\n }}\n \
try {{\n $text = \\FFI::string($ptr);\n }} finally {{\n \
self::$ffi->rust_anything_free($ptr);\n }}\n \
$answer = \\json_decode($text, true, Codec::DEPTH, \\JSON_THROW_ON_ERROR);\n \
if (\\array_key_exists('ok', $answer)) {{\n return Codec::dec($answer['ok']);\n }}\n \
if (\\array_key_exists('panic', $answer)) {{\n \
throw new \\Error('Rust panic: ' . $answer['panic']);\n }}\n \
throw Codec::error((string) $answer['error']);\n }}\n }}\n}}\n",
unit = m.unit,
);
let mut by_ns: Vec<(String, Vec<String>)> = Vec::new();
for f in &m.exports {
let (ns, _) = qualified(f);
let args: Vec<String> = f.params.iter().map(|p| format!("${}", p.name)).collect();
let def = format!(
"function {name}({sig})\n{{\n return \\RustAnything\\{class}::call('{name}', [{args}]);\n}}",
name = f.name,
sig = signature(f),
args = args.join(", "),
);
match by_ns.iter_mut().find(|(n, _)| *n == ns) {
Some((_, defs)) => defs.push(def),
None => by_ns.push((ns, vec![def])),
}
}
for (ns, defs) in by_ns {
let head = if ns.is_empty() {
"namespace {".to_string()
} else {
format!("namespace {ns} {{")
};
let _ = writeln!(out, "\n{head}");
for (i, def) in defs.iter().enumerate() {
if i > 0 {
out.push('\n');
}
for line in def.lines() {
let _ = writeln!(out, " {line}");
}
}
out.push_str("}\n");
}
out
}
pub fn targets(m: &Manifest) -> serde_json::Value {
serde_json::Value::Object(
m.exports
.iter()
.map(|f| (f.name.clone(), serde_json::Value::String(qualified(f).1)))
.collect(),
)
}
pub fn driver() -> String {
format!("<?php\n\n{CODEC_PHP}\n{DRIVER_PHP}")
}
const DRIVER_PHP: &str = r#"namespace {
use RustAnything\Codec;
\ini_set('display_errors', 'stderr');
[, $mode, $targetsPath, $casesPath, $outPath, $minMs] = $argv;
$autoload = \getenv('RUST_ANYTHING_PHP_AUTOLOAD');
if ($autoload !== false && $autoload !== '') {
require_once $autoload;
}
foreach (\array_slice($argv, 6) as $file) {
require_once $file;
}
$targets = \json_decode(\file_get_contents($targetsPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
function rust_anything_args(string $target, array $c): array
{
$args = $c['args'] ?? [];
while ($args && \is_array(\end($args)) && \array_key_exists('$undefined', \end($args))) {
\array_pop($args);
}
$params = null;
$out = [];
$named = false;
foreach (\array_values($args) as $i => $arg) {
if (\is_array($arg) && \count($arg) === 1 && \array_key_exists('$undefined', $arg)) {
$named = true;
continue;
}
if ($named) {
$params ??= (new \ReflectionFunction($target))->getParameters();
$out[isset($params[$i]) ? $params[$i]->getName() : $i] = Codec::dec($arg);
} else {
$out[] = Codec::dec($arg);
}
}
return $out;
}
function rust_anything_call(string $target, array $c): array
{
\ob_start();
try {
$result = ['ok' => Codec::enc($target(...rust_anything_args($target, $c)))];
} catch (\Throwable $e) {
$result = ['error' => $e->getMessage(), 'error_type' => \get_class($e)];
} finally {
$output = \ob_get_clean();
}
if (\is_string($output) && $output !== '') {
$result['output'] = $output;
}
return $result;
}
function rust_anything_lines(string $path): array
{
$out = [];
foreach (\file($path, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES) as $line) {
$out[] = \json_decode($line, true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
}
return $out;
}
function rust_anything_same(array $expected, array $got): bool
{
if (\str_starts_with((string) ($got['error'] ?? ''), 'Rust panic:')) {
return false;
}
if (($expected['output'] ?? '') !== ($got['output'] ?? '')) {
return false;
}
if (\array_key_exists('error', $expected)) {
return \array_key_exists('error', $got) && $expected['error_type'] === $got['error_type'];
}
return !\array_key_exists('error', $got)
&& \json_encode($expected['ok'], Codec::FLAGS) === \json_encode($got['ok'], Codec::FLAGS);
}
switch ($mode) {
case 'record':
$progress = \getenv('RUST_ANYTHING_PROGRESS');
$out = \fopen($outPath, 'w');
$cases = \json_decode(\file_get_contents($casesPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
foreach ($cases as $index => $c) {
if ($progress !== false && $progress !== '') {
\file_put_contents($progress, "$index\n", \FILE_APPEND);
}
$line = ['fn' => $c['fn'], 'args' => $c['args'] ?? []] + rust_anything_call($targets[$c['fn']], $c);
try {
\fwrite($out, \json_encode($line, Codec::FLAGS) . "\n");
\fflush($out);
} catch (\JsonException $e) {
continue;
}
}
\fclose($out);
break;
case 'diff':
$summary = ['total' => 0, 'passed' => 0, 'failed' => 0, 'missing' => [], 'mismatches' => []];
foreach (rust_anything_lines($casesPath) as $c) {
$summary['total']++;
$got = rust_anything_call($targets[$c['fn']], $c);
$expected = \array_intersect_key($c, ['ok' => 1, 'error' => 1, 'error_type' => 1, 'output' => 1]);
if (rust_anything_same($expected, $got)) {
$summary['passed']++;
} else {
$summary['failed']++;
$summary['mismatches'][] = ['fn' => $c['fn'], 'args' => $c['args'], 'expected' => $expected, 'actual' => $got];
}
}
\file_put_contents($outPath, \json_encode($summary, Codec::FLAGS | \JSON_INVALID_UTF8_SUBSTITUTE));
break;
case 'bench':
$groups = [];
foreach (rust_anything_lines($casesPath) as $c) {
$groups[$c['fn']][] = rust_anything_args($targets[$c['fn']], $c);
}
$result = [];
foreach ($groups as $name => $prepared) {
$target = $targets[$name];
$once = function () use ($target, $prepared) {
\ob_start();
foreach ($prepared as $args) {
try {
$target(...$args);
} catch (\Throwable $e) {
}
}
\ob_end_clean();
};
$once();
$passes = 0;
$start = \hrtime(true);
while (true) {
$once();
$passes++;
$elapsed = \hrtime(true) - $start;
if ($elapsed / 1e6 >= (int) $minMs) {
$result[$name] = ['cases' => \count($prepared), 'ns' => $elapsed / ($passes * \count($prepared))];
break;
}
}
}
\file_put_contents($outPath, \json_encode((object) $result, Codec::FLAGS));
break;
}
}
"#;