Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
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)
}
/// One generated function or method. The signature can carry a multiline default copied from the
/// source; the writer must not indent its continuation lines, or the spaces become string content.
struct Entry {
signature: String,
body: String,
}
/// A wrapper entry: a top-level function, or the static methods of one class.
enum Def {
Function(Entry),
Class { name: String, methods: Vec<Entry> },
}
/// Write an entry with `indent` at the start of its signature and body lines. The signature's
/// continuation lines are written as they are: a multiline string default keeps its bytes, and a
/// multiline array or heredoc default stays valid PHP.
fn write_entry(out: &mut String, entry: &Entry, indent: &str) {
let mut signature = entry.signature.split('\n');
if let Some(first) = signature.next() {
let _ = writeln!(out, "{indent}{first}");
}
for line in signature {
let _ = writeln!(out, "{line}");
}
for line in entry.body.lines() {
let _ = writeln!(out, "{indent}{line}");
}
}
/// The class a static method belongs to (`Acme\Text\Words::count` → `Words`).
fn method_class(f: &ExportedFn) -> Option<String> {
let (_, full) = qualified(f);
let (class, _) = full.split_once("::")?;
class.rsplit('\\').next().map(str::to_string)
}
/// The variable that holds the dispatcher's response. A parameter with the same name would
/// overwrite it on write-back (`$answer = $answer['after'][0]`), so pick one no parameter uses.
fn response_var(f: &ExportedFn) -> String {
let mut name = "__response".to_string();
while f.params.iter().any(|p| p.name == name) {
name.insert(0, '_');
}
format!("${name}")
}
pub fn wrapper(m: &Manifest, api: &crate::codegen::PortApi) -> String {
let (dylib, dll, so) = library_names(m);
let class = native_class(m);
// Issue #1198: what stays in PHP is not in this file, which replaces the original.
let kept = crate::bridge::kept_header(&m.js_only, "PHP");
let mut out = format!(
"<?php\n\n\
// The Rust port of `{unit}`, generated by rust-anything: the same functions and static\n\
// methods, each calling the Rust library through PHP's FFI extension. Require it in place\n\
// of the original files it bridges; classes kept in PHP stay in their own files.\n\
// Outside the CLI, PHP allows FFI only with ffi.enable=true in php.ini: the default,\n\
// \"preload\", allows it in the CLI and in preloaded scripts only.\n\
// Regenerate with `rust-anything refresh`.\n\
{kept}\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 \
if (!\\extension_loaded('ffi')) {{\n \
throw new \\RuntimeException('rust-anything: this PHP has no FFI extension, which the Rust port is called through');\n }}\n \
$lib = \\PHP_OS_FAMILY === 'Darwin' ? '{dylib}' : (\\PHP_OS_FAMILY === 'Windows' ? '{dll}' : '{so}');\n \
try {{\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 \
}} catch (\\FFI\\Exception $e) {{\n \
if (!\\str_contains($e->getMessage(), 'ffi.enable')) {{\n throw $e;\n }}\n \
throw new \\RuntimeException(\n \
'rust-anything: PHP refused FFI under ' . \\PHP_SAPI . ' (ffi.enable=' . \\ini_get('ffi.enable') . '). '\n \
. 'Outside the CLI the default ffi.enable=preload allows FFI only in preloaded scripts: set ffi.enable=true in the php.ini of this SAPI to call the Rust port.',\n \
0,\n \
$e\n );\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<Def>)> = 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 method = method_class(f);
let vis = if method.is_some() {
"public static "
} else {
""
};
let php_name = f.name.rsplit_once("::").map_or(f.name.as_str(), |(_, m)| m);
let signature = format!("{vis}function {php_name}({sig})", sig = signature(f),);
let body = if !f.mutates.is_empty() || f.prints {
// The dispatcher answers `{ret, after, error, stdout}`: each parameter taken by
// reference gets its value after the call, the text is echoed, then the result is
// returned or the error thrown.
let response = response_var(f);
let writes: String = crate::codegen::changed_params(f, api)
.into_iter()
.map(|(n, p)| format!(" ${} = {response}['after'][{n}];\n", p.name))
.collect();
format!(
"{{\n {response} = \\RustAnything\\{class}::call('{name}', [{args}]);\n{writes} \
if ({response}['stdout'] !== '') {{\n echo {response}['stdout'];\n }}\n \
if ({response}['error'] !== null) {{\n throw \\RustAnything\\Codec::error((string) {response}['error']);\n }}\n \
return {response}['ret'];\n}}",
name = f.name,
args = args.join(", "),
)
} else {
format!(
"{{\n return \\RustAnything\\{class}::call('{name}', [{args}]);\n}}",
name = f.name,
args = args.join(", "),
)
};
let entry = Entry { signature, body };
let ns_index = match by_ns.iter().position(|(n, _)| *n == ns) {
Some(i) => i,
None => {
by_ns.push((ns, Vec::new()));
by_ns.len() - 1
}
};
let defs = &mut by_ns[ns_index].1;
match method {
Some(class) => {
if let Some(Def::Class { methods, .. }) = defs
.iter_mut()
.find(|d| matches!(d, Def::Class { name, .. } if *name == class))
{
methods.push(entry);
} else {
defs.push(Def::Class {
name: class,
methods: vec![entry],
});
}
}
None => defs.push(Def::Function(entry)),
}
}
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');
}
match def {
Def::Function(entry) => write_entry(&mut out, entry, " "),
Def::Class { name, methods } => {
let _ = writeln!(out, " final class {name}\n {{");
for (n, method) in methods.iter().enumerate() {
if n > 0 {
out.push('\n');
}
write_entry(&mut out, method, " ");
}
out.push_str(" }\n");
}
}
}
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;
}
$classmapPath = \getenv('RUST_ANYTHING_PHP_CLASSMAP');
if ($classmapPath !== false && $classmapPath !== '') {
$classmap = \json_decode(\file_get_contents($classmapPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
\spl_autoload_register(static function (string $name) use ($classmap): void {
$file = $classmap[\strtolower($name)] ?? null;
if ($file !== null) {
require_once $file;
}
});
}
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_params(string $target): array
{
if (\str_contains($target, '::')) {
[$class, $method] = \explode('::', $target, 2);
return (new \ReflectionMethod($class, $method))->getParameters();
}
return (new \ReflectionFunction($target))->getParameters();
}
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 ??= rust_anything_params($target);
$out[isset($params[$i]) ? $params[$i]->getName() : $i] = Codec::dec($arg);
} else {
$out[] = Codec::dec($arg);
}
}
return $out;
}
function rust_anything_state(array $args): string
{
return \json_encode(Codec::enc($args), Codec::FLAGS | \JSON_INVALID_UTF8_SUBSTITUTE | \JSON_PARTIAL_OUTPUT_ON_ERROR);
}
// `fx` is what the call changed besides returning: the arguments it took by reference, after it
// (`args_after`, only when they changed). `now` is the arguments after the call, for a mismatch.
function rust_anything_call(string $target, array $c): array
{
$args = rust_anything_args($target, $c);
$before = rust_anything_state($args);
\ob_start();
try {
$result = ['ok' => Codec::enc($target(...$args))];
} 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;
}
$result['now'] = Codec::enc($args);
$result['fx'] = rust_anything_state($args) !== $before ? ['args_after' => $result['now']] : [];
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']
&& (\getenv('RUST_ANYTHING_MESSAGES') !== '1' || $expected['error'] === $got['error']);
}
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);
}
$result = rust_anything_call($targets[$c['fn']], $c);
$fx = $result['fx'];
unset($result['fx'], $result['now']);
// `post`: this line holds what the call changed, so the port is compared on it.
$line = ['fn' => $c['fn'], 'args' => $c['args'] ?? []] + $result + ['post' => true] + $fx;
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' => [], 'legacy_cases' => 0];
foreach (rust_anything_lines($casesPath) as $c) {
$summary['total']++;
$target = $targets[$c['fn']] ?? null;
if (!\is_string($target) || !\is_callable($target)) {
if (!\in_array($c['fn'], $summary['missing'], true)) {
$summary['missing'][] = $c['fn'];
}
$summary['failed']++;
$expected = \array_intersect_key($c, ['ok' => 1, 'error' => 1, 'error_type' => 1, 'output' => 1]);
$summary['mismatches'][] = ['fn' => $c['fn'], 'args' => $c['args'] ?? [], 'expected' => $expected, 'actual' => ['missing' => true]];
continue;
}
$got = rust_anything_call($target, $c);
$fx = $got['fx'];
$now = $got['now'];
unset($got['fx'], $got['now']);
$expected = \array_intersect_key($c, ['ok' => 1, 'error' => 1, 'error_type' => 1, 'output' => 1]);
$effectsSame = true;
if ($c['post'] ?? false) {
if (\array_key_exists('args_after', $c)) {
$expected['args_after'] = $c['args_after'];
// A mismatch shows the arguments after the call, changed or not.
$got['args_after'] = $fx['args_after'] ?? $now;
} elseif (\array_key_exists('args_after', $fx)) {
$got['args_after'] = $fx['args_after'];
}
$effectsSame = \json_encode($c['args_after'] ?? null, Codec::FLAGS) === \json_encode($fx['args_after'] ?? null, Codec::FLAGS);
} else {
$summary['legacy_cases']++;
}
if ($effectsSame && 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;
}
}
"#;
#[cfg(test)]
mod tests {
use super::*;
use crate::ts::exports::Param;
fn manifest() -> Manifest {
Manifest {
schema: String::new(),
root: std::path::PathBuf::new(),
root_written: None,
unit: "src/Words.php".into(),
language: crate::lang::Lang::Php,
kind: crate::bridge::Kind::Ffi,
crate_name: "static-text-rs".into(),
exports: Vec::new(),
classes: Vec::new(),
js_only: Vec::new(),
batches: Vec::new(),
allocator: Default::default(),
float_tolerance: None,
ignore_key_order: false,
messages: false,
end_state: None,
}
}
fn method(name: &str, prototype: &str) -> ExportedFn {
ExportedFn {
name: name.into(),
prototype: Some(prototype.into()),
params: vec![Param {
name: "text".into(),
ts_type: "string".into(),
..Default::default()
}],
..Default::default()
}
}
#[test]
fn qualified_splits_namespaces_and_falls_back_to_name() {
let fn_with = |name: &str, prototype: Option<&str>| ExportedFn {
name: name.into(),
prototype: prototype.map(Into::into),
..Default::default()
};
// Fallback to name when prototype is None
assert_eq!(
qualified(&fn_with("slugify", None)),
(String::new(), "slugify".into())
);
// No namespace in prototype
assert_eq!(
qualified(&fn_with("slugify", Some("slugify(string $s)"))),
(String::new(), "slugify".into())
);
// One level namespace
assert_eq!(
qualified(&fn_with("slugify", Some(r"Text\slugify(string $s)"))),
("Text".into(), r"Text\slugify".into())
);
// Several levels namespace
assert_eq!(
qualified(&fn_with("slugify", Some(r"Acme\Text\slugify(string $s)"))),
(r"Acme\Text".into(), r"Acme\Text\slugify".into())
);
// Prototype with spaces before '('
assert_eq!(
qualified(&fn_with(
"slugify",
Some(r"Acme\Text\slugify (string $s)")
)),
(r"Acme\Text".into(), r"Acme\Text\slugify".into())
);
// A static method keeps its class in the callable name.
assert_eq!(
qualified(&fn_with(
"count",
Some(r"Acme\StaticText\Words::count(string $s)")
)),
(
r"Acme\StaticText".into(),
r"Acme\StaticText\Words::count".into()
)
);
}
#[test]
fn the_header_names_what_stays_in_php() {
// Issue #1198: the wrapper is required in place of the original, which also holds these.
let mut m = manifest();
let header = |m: &Manifest| -> String {
let w = wrapper(m, &Default::default());
w.split("namespace ").next().unwrap_or_default().to_string()
};
assert!(!header(&m).contains("Kept in PHP"), "{}", header(&m));
m.js_only = vec![
crate::bridge::JsOnly {
name: "total".into(),
file: "src/text.php".into(),
line: 3,
reason: "takes `...$args`".into(),
},
crate::bridge::JsOnly {
name: "each".into(),
file: "src/text.php".into(),
line: 9,
reason: "takes a callback".into(),
},
];
assert!(
header(&m).contains(
"// Kept in PHP and not defined here: `total` and `each`. Move what is kept out of the \
original before this file replaces it.\n"
),
"{}",
header(&m)
);
}
#[test]
fn static_methods_are_written_as_a_class() {
let mut m = manifest();
m.exports = vec![
method("count", r"Acme\StaticText\Words::count(string $text)"),
method("clamp", r"Acme\StaticText\Words::clamp(int $value)"),
method("slugify", r"Acme\Text\slugify(string $text)"),
method("globalCount", r"GlobalWords::globalCount(string $text)"),
];
let w = wrapper(&m, &Default::default());
assert!(w.contains("namespace Acme\\StaticText {"), "{w}");
assert!(w.contains("namespace Acme\\Text {"), "{w}");
assert!(w.contains("final class Words"), "{w}");
assert!(
w.contains("public static function count(string $text)"),
"{w}"
);
assert!(
w.contains("public static function clamp(int $value)"),
"{w}"
);
assert!(
w.contains(r"\RustAnything\NativeStaticTextRs::call('count', [$text]);"),
"{w}"
);
assert!(w.contains("function slugify(string $text)"), "{w}");
assert!(!w.contains("public static function slugify"), "{w}");
assert!(
w.contains("namespace {\n final class GlobalWords"),
"{w}"
);
assert_eq!(w.matches("final class Words").count(), 1, "{w}");
}
#[test]
fn a_parameter_named_answer_cannot_shadow_the_response() {
let mut m = manifest();
let mut f = method("bump", r"Acme\bump(int &$answer)");
f.params = vec![Param {
name: "answer".into(),
ts_type: "int".into(),
..Default::default()
}];
f.mutates = vec!["answer".into()];
m.exports = vec![f];
let w = wrapper(&m, &Default::default());
assert!(w.contains("$__response = \\RustAnything"), "{w}");
assert!(w.contains("$answer = $__response['after'][0]"), "{w}");
assert!(w.contains("return $__response['ret']"), "{w}");
}
#[test]
fn the_response_variable_avoids_every_parameter_name() {
let mut m = manifest();
let mut f = method("bump", r"Acme\bump(int &$__response)");
f.params = vec![Param {
name: "__response".into(),
ts_type: "int".into(),
..Default::default()
}];
f.mutates = vec!["__response".into()];
m.exports = vec![f];
let w = wrapper(&m, &Default::default());
assert!(w.contains("$___response = \\RustAnything"), "{w}");
assert!(w.contains("$__response = $___response['after'][0]"), "{w}");
assert!(w.contains("return $___response['ret']"), "{w}");
}
#[test]
fn a_default_that_ends_in_a_parenthesis_is_written_whole() {
let mut m = manifest();
m.exports = crate::lang::php::exports(
"src/Def.php",
"<?php final class Def { public static function size(array $xs = array()): int { return count($xs); } }",
);
let w = wrapper(&m, &Default::default());
assert!(
w.contains("public static function size(array $xs = array())"),
"{w}"
);
}
#[test]
fn a_multiline_string_default_keeps_its_bytes() {
let mut m = manifest();
m.exports = crate::lang::php::exports(
"src/Def.php",
"<?php final class Def { public static function text(string $s = \"first\nnew Value()\nthird\"): string { return $s; } }",
);
let w = wrapper(&m, &Default::default());
assert!(
w.contains("public static function text(string $s = \"first\nnew Value()\nthird\")"),
"{w}"
);
m.exports = crate::lang::php::exports(
"src/f.php",
"<?php function text(string $s = \"first\nnew Value()\nthird\"): string { return $s; }",
);
let w = wrapper(&m, &Default::default());
assert!(
w.contains("function text(string $s = \"first\nnew Value()\nthird\")"),
"{w}"
);
}
#[test]
fn a_static_method_target_is_its_qualified_callable() {
let mut m = manifest();
m.exports = vec![method(
"count",
r"Acme\StaticText\Words::count(string $text)",
)];
assert_eq!(targets(&m)["count"], r"Acme\StaticText\Words::count");
}
#[test]
fn diff_counts_a_case_whose_function_is_gone_as_missing() {
if !crate::setup::on_path("php") {
return;
}
let dir = crate::app::temp_dir("php-missing-target").unwrap();
std::fs::write(dir.join("driver.php"), driver()).unwrap();
std::fs::write(
dir.join("unit.php"),
"<?php\nfunction twice($x) { return $x * 2; }\n",
)
.unwrap();
std::fs::write(dir.join("targets.json"), r#"{"twice": "twice"}"#).unwrap();
std::fs::write(
dir.join("cases.jsonl"),
"{\"fn\":\"twice\",\"args\":[2],\"ok\":4}\n{\"fn\":\"gone\",\"args\":[1],\"ok\":1}\n",
)
.unwrap();
let ran = std::process::Command::new("php")
.arg(dir.join("driver.php"))
.arg("diff")
.arg(dir.join("targets.json"))
.arg(dir.join("cases.jsonl"))
.arg(dir.join("out.json"))
.arg("0")
.arg(dir.join("unit.php"))
.output()
.unwrap();
let out = std::fs::read_to_string(dir.join("out.json"));
let _ = std::fs::remove_dir_all(&dir);
assert!(
ran.status.success(),
"{}",
String::from_utf8_lossy(&ran.stderr)
);
let summary: serde_json::Value = serde_json::from_str(&out.unwrap()).unwrap();
assert_eq!(summary["total"], 2);
assert_eq!(summary["passed"], 1);
assert_eq!(summary["failed"], 1);
assert_eq!(summary["missing"], serde_json::json!(["gone"]));
}
#[test]
fn changed_arguments_are_read_by_the_ports_mut_parameters() {
let param = |name: &str| crate::ts::exports::Param {
name: name.into(),
..Default::default()
};
let m = Manifest {
schema: String::new(),
root: std::path::PathBuf::new(),
root_written: None,
unit: "src/fill.php".into(),
language: crate::lang::Lang::Php,
kind: crate::bridge::Kind::Ffi,
crate_name: "fill-rs".into(),
exports: vec![crate::ts::exports::ExportedFn {
name: "fill".into(),
params: vec![param("a"), param("b"), param("c")],
mutates: vec!["a".into(), "c".into()],
..Default::default()
}],
classes: Vec::new(),
js_only: Vec::new(),
batches: Vec::new(),
allocator: Default::default(),
float_tolerance: None,
ignore_key_order: false,
messages: false,
end_state: None,
};
let api = crate::codegen::PortApi {
functions: vec![crate::codegen::PortFn {
js_name: "fill".into(),
rust_name: "fill".into(),
params: vec![
("a".into(), "Vec<i64>".into()),
("b".into(), "&mut Vec<i64>".into()),
("stdout".into(), "&mut String".into()),
("c".into(), "&mut Vec<i64>".into()),
],
ret: "()".into(),
fallible: false,
is_async: false,
}],
..Default::default()
};
let php = wrapper(&m, &api);
assert!(!php.contains("$a = $__response['after']"), "{php}");
assert!(php.contains("$b = $__response['after'][0];"), "{php}");
assert!(php.contains("$c = $__response['after'][1];"), "{php}");
let fallback = wrapper(&m, &Default::default());
assert!(
fallback.contains("$a = $__response['after'][0];"),
"{fallback}"
);
assert!(
fallback.contains("$c = $__response['after'][1];"),
"{fallback}"
);
}
#[test]
fn the_wrapper_names_ffi_enable_when_ffi_is_refused() {
let m = Manifest {
schema: String::new(),
root: std::path::PathBuf::new(),
root_written: None,
unit: "src/pad.php".into(),
language: crate::lang::Lang::Php,
kind: crate::bridge::Kind::Ffi,
crate_name: "pad-rs".into(),
exports: Vec::new(),
classes: Vec::new(),
js_only: Vec::new(),
batches: Vec::new(),
allocator: Default::default(),
float_tolerance: None,
ignore_key_order: false,
messages: false,
end_state: None,
};
let php = wrapper(&m, &Default::default());
assert!(php.contains("} catch (\\FFI\\Exception $e) {"), "{php}");
assert!(php.contains("ffi.enable"), "{php}");
if crate::setup::on_path("php") {
let dir = crate::app::temp_dir("php-wrapper-lint").unwrap();
std::fs::write(dir.join("pad.php"), &php).unwrap();
let lint = std::process::Command::new("php")
.arg("-l")
.arg(dir.join("pad.php"))
.output()
.unwrap();
let _ = std::fs::remove_dir_all(&dir);
assert!(lint.status.success(), "{php}");
}
}
#[test]
fn clashing_static_methods_keep_bare_php_names_and_write_back_right_by_ref_param() {
let mut m = manifest();
m.exports = vec![
ExportedFn {
name: "First::fill".into(),
prototype: Some(r"Acme\Clash\First::fill(array &$a, int $n)".into()),
params: vec![
Param {
name: "a".into(),
ts_type: "number[]".into(),
..Default::default()
},
Param {
name: "n".into(),
ts_type: "number".into(),
..Default::default()
},
],
mutates: vec!["a".into()],
..Default::default()
},
ExportedFn {
name: "Second::fill".into(),
prototype: Some(r"Acme\Clash\Second::fill(int $n, array &$b)".into()),
params: vec![
Param {
name: "n".into(),
ts_type: "number".into(),
..Default::default()
},
Param {
name: "b".into(),
ts_type: "number[]".into(),
..Default::default()
},
],
mutates: vec!["b".into()],
..Default::default()
},
];
let api = crate::codegen::PortApi {
functions: vec![
crate::codegen::PortFn {
js_name: "First::fill".into(),
rust_name: "first_fill".into(),
params: vec![
("a".into(), "&mut Vec<i64>".into()),
("n".into(), "i64".into()),
],
ret: "()".into(),
fallible: false,
is_async: false,
},
crate::codegen::PortFn {
js_name: "Second::fill".into(),
rust_name: "second_fill".into(),
params: vec![
("n".into(), "i64".into()),
("b".into(), "&mut Vec<i64>".into()),
],
ret: "()".into(),
fallible: false,
is_async: false,
},
],
..Default::default()
};
let php = wrapper(&m, &api);
assert_eq!(
php.matches("public static function fill(").count(),
2,
"{php}"
);
assert!(php.contains("call('First::fill', [$a, $n])"), "{php}");
assert!(php.contains("$a = $__response['after'][0];"), "{php}");
assert!(php.contains("call('Second::fill', [$n, $b])"), "{php}");
assert!(php.contains("$b = $__response['after'][0];"), "{php}");
let targets = targets(&m);
assert_eq!(targets["First::fill"], r"Acme\Clash\First::fill");
assert_eq!(targets["Second::fill"], r"Acme\Clash\Second::fill");
}
}