1use std::fmt::Write as _;
2
3use crate::bridge::Manifest;
4use crate::ts::exports::ExportedFn;
5
6const CODEC_PHP: &str = r#"namespace RustAnything {
7 if (!\class_exists(Codec::class, false)) {
8 final class Codec
9 {
10 public const FLAGS = \JSON_PRESERVE_ZERO_FRACTION | \JSON_THROW_ON_ERROR
11 | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE;
12 public const DEPTH = 100000;
13
14 public static function enc($v)
15 {
16 if (\is_float($v)) {
17 if (\is_nan($v)) {
18 return ['$num' => 'NaN'];
19 }
20 if (\is_infinite($v)) {
21 return ['$num' => $v > 0 ? 'Infinity' : '-Infinity'];
22 }
23 if ($v == 0.0 && \fdiv(1.0, $v) < 0) {
24 return ['$num' => '-0'];
25 }
26 return $v;
27 }
28 if (\is_array($v)) {
29 $out = [];
30 foreach ($v as $k => $x) {
31 $out[$k] = self::enc($x);
32 }
33 return $out;
34 }
35 if (\is_object($v)) {
36 return ['$object' => \get_class($v)];
37 }
38 if (\is_resource($v)) {
39 return ['$resource' => \get_resource_type($v)];
40 }
41 return $v;
42 }
43
44 public static function dec($v)
45 {
46 if (!\is_array($v)) {
47 return $v;
48 }
49 if (\count($v) === 1 && \array_key_exists('$num', $v)) {
50 return ['NaN' => \NAN, 'Infinity' => \INF, '-Infinity' => -\INF, '-0' => -0.0][$v['$num']];
51 }
52 if (\count($v) === 1 && \array_key_exists('$undefined', $v)) {
53 return null;
54 }
55 $out = [];
56 foreach ($v as $k => $x) {
57 $out[$k] = self::dec($x);
58 }
59 return $out;
60 }
61
62 public static function json($v): string
63 {
64 return \json_encode(self::enc($v), self::FLAGS);
65 }
66
67 public static function error(string $message): \Throwable
68 {
69 if (\preg_match('/^\\\\?([A-Za-z_][A-Za-z0-9_]*(?:\\\\[A-Za-z_][A-Za-z0-9_]*)*): (.*)$/s', $message, $m)
70 && \class_exists($m[1])
71 && \is_subclass_of($m[1], \Throwable::class)
72 ) {
73 try {
74 return new $m[1]($m[2]);
75 } catch (\Throwable $e) {
76 }
77 }
78 return new \RuntimeException($message);
79 }
80 }
81 }
82}
83"#;
84
85pub fn wrapper_path(m: &Manifest) -> String {
86 format!("php/{}.php", m.lib_name())
87}
88
89fn library_names(m: &Manifest) -> (String, String, String) {
90 let lib = m.lib_name();
91 (
92 format!("lib{lib}.dylib"),
93 format!("{lib}.dll"),
94 format!("lib{lib}.so"),
95 )
96}
97
98pub fn native_class(m: &Manifest) -> String {
99 format!("Native{}", crate::codegen_ruby::camel(&m.lib_name()))
100}
101
102pub fn qualified(f: &ExportedFn) -> (String, String) {
103 let proto = f.prototype.as_deref().unwrap_or(&f.name);
104 let head = proto.split('(').next().unwrap_or(proto).trim();
105 match head.rsplit_once('\\') {
106 Some((ns, _)) => (ns.to_string(), head.to_string()),
107 None => (String::new(), head.to_string()),
108 }
109}
110
111fn signature(f: &ExportedFn) -> String {
112 crate::lang::ruby::signature(f)
113}
114
115pub fn wrapper(m: &Manifest) -> String {
116 let (dylib, dll, so) = library_names(m);
117 let class = native_class(m);
118 let mut out = format!(
119 "<?php\n\n\
120 // The Rust port of `{unit}`, generated by rust-anything: the same functions, each calling the\n\
121 // Rust library through PHP's FFI extension. Require it in place of the original files.\n\
122 // Regenerate with `rust-anything refresh`.\n\n\
123 {CODEC_PHP}\n\
124 namespace RustAnything {{\n \
125 final class {class}\n {{\n \
126 private static $ffi = null;\n\n \
127 public static function call(string $name, array $args)\n {{\n \
128 if (self::$ffi === null) {{\n \
129 $lib = \\PHP_OS_FAMILY === 'Darwin' ? '{dylib}' : (\\PHP_OS_FAMILY === 'Windows' ? '{dll}' : '{so}');\n \
130 self::$ffi = \\FFI::cdef(\n \
131 'char *rust_anything_call(const char *name, const char *args); void rust_anything_free(char *ptr);',\n \
132 __DIR__ . '/' . $lib\n );\n }}\n \
133 $ptr = self::$ffi->rust_anything_call($name, Codec::json($args));\n \
134 if ($ptr === null) {{\n \
135 throw new \\RuntimeException(\"rust-anything: no answer from `$name`\");\n }}\n \
136 try {{\n $text = \\FFI::string($ptr);\n }} finally {{\n \
137 self::$ffi->rust_anything_free($ptr);\n }}\n \
138 $answer = \\json_decode($text, true, Codec::DEPTH, \\JSON_THROW_ON_ERROR);\n \
139 if (\\array_key_exists('ok', $answer)) {{\n return Codec::dec($answer['ok']);\n }}\n \
140 if (\\array_key_exists('panic', $answer)) {{\n \
141 throw new \\Error('Rust panic: ' . $answer['panic']);\n }}\n \
142 throw Codec::error((string) $answer['error']);\n }}\n }}\n}}\n",
143 unit = m.unit,
144 );
145 let mut by_ns: Vec<(String, Vec<String>)> = Vec::new();
146 for f in &m.exports {
147 let (ns, _) = qualified(f);
148 let args: Vec<String> = f.params.iter().map(|p| format!("${}", p.name)).collect();
149 let def = format!(
150 "function {name}({sig})\n{{\n return \\RustAnything\\{class}::call('{name}', [{args}]);\n}}",
151 name = f.name,
152 sig = signature(f),
153 args = args.join(", "),
154 );
155 match by_ns.iter_mut().find(|(n, _)| *n == ns) {
156 Some((_, defs)) => defs.push(def),
157 None => by_ns.push((ns, vec![def])),
158 }
159 }
160 for (ns, defs) in by_ns {
161 let head = if ns.is_empty() {
162 "namespace {".to_string()
163 } else {
164 format!("namespace {ns} {{")
165 };
166 let _ = writeln!(out, "\n{head}");
167 for (i, def) in defs.iter().enumerate() {
168 if i > 0 {
169 out.push('\n');
170 }
171 for line in def.lines() {
172 let _ = writeln!(out, " {line}");
173 }
174 }
175 out.push_str("}\n");
176 }
177 out
178}
179
180pub fn targets(m: &Manifest) -> serde_json::Value {
181 serde_json::Value::Object(
182 m.exports
183 .iter()
184 .map(|f| (f.name.clone(), serde_json::Value::String(qualified(f).1)))
185 .collect(),
186 )
187}
188
189pub fn driver() -> String {
190 format!("<?php\n\n{CODEC_PHP}\n{DRIVER_PHP}")
191}
192
193const DRIVER_PHP: &str = r#"namespace {
194 use RustAnything\Codec;
195
196 \ini_set('display_errors', 'stderr');
197 [, $mode, $targetsPath, $casesPath, $outPath, $minMs] = $argv;
198 $autoload = \getenv('RUST_ANYTHING_PHP_AUTOLOAD');
199 if ($autoload !== false && $autoload !== '') {
200 require_once $autoload;
201 }
202 foreach (\array_slice($argv, 6) as $file) {
203 require_once $file;
204 }
205 $targets = \json_decode(\file_get_contents($targetsPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
206
207 function rust_anything_args(string $target, array $c): array
208 {
209 $args = $c['args'] ?? [];
210 while ($args && \is_array(\end($args)) && \array_key_exists('$undefined', \end($args))) {
211 \array_pop($args);
212 }
213 $params = null;
214 $out = [];
215 $named = false;
216 foreach (\array_values($args) as $i => $arg) {
217 if (\is_array($arg) && \count($arg) === 1 && \array_key_exists('$undefined', $arg)) {
218 $named = true;
219 continue;
220 }
221 if ($named) {
222 $params ??= (new \ReflectionFunction($target))->getParameters();
223 $out[isset($params[$i]) ? $params[$i]->getName() : $i] = Codec::dec($arg);
224 } else {
225 $out[] = Codec::dec($arg);
226 }
227 }
228 return $out;
229 }
230
231 function rust_anything_call(string $target, array $c): array
232 {
233 \ob_start();
234 try {
235 $result = ['ok' => Codec::enc($target(...rust_anything_args($target, $c)))];
236 } catch (\Throwable $e) {
237 $result = ['error' => $e->getMessage(), 'error_type' => \get_class($e)];
238 } finally {
239 $output = \ob_get_clean();
240 }
241 if (\is_string($output) && $output !== '') {
242 $result['output'] = $output;
243 }
244 return $result;
245 }
246
247 function rust_anything_lines(string $path): array
248 {
249 $out = [];
250 foreach (\file($path, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES) as $line) {
251 $out[] = \json_decode($line, true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
252 }
253 return $out;
254 }
255
256 function rust_anything_same(array $expected, array $got): bool
257 {
258 if (\str_starts_with((string) ($got['error'] ?? ''), 'Rust panic:')) {
259 return false;
260 }
261 if (($expected['output'] ?? '') !== ($got['output'] ?? '')) {
262 return false;
263 }
264 if (\array_key_exists('error', $expected)) {
265 return \array_key_exists('error', $got) && $expected['error_type'] === $got['error_type'];
266 }
267 return !\array_key_exists('error', $got)
268 && \json_encode($expected['ok'], Codec::FLAGS) === \json_encode($got['ok'], Codec::FLAGS);
269 }
270
271 switch ($mode) {
272 case 'record':
273 $progress = \getenv('RUST_ANYTHING_PROGRESS');
274 $out = \fopen($outPath, 'w');
275 $cases = \json_decode(\file_get_contents($casesPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
276 foreach ($cases as $index => $c) {
277 if ($progress !== false && $progress !== '') {
278 \file_put_contents($progress, "$index\n", \FILE_APPEND);
279 }
280 $line = ['fn' => $c['fn'], 'args' => $c['args'] ?? []] + rust_anything_call($targets[$c['fn']], $c);
281 try {
282 \fwrite($out, \json_encode($line, Codec::FLAGS) . "\n");
283 \fflush($out);
284 } catch (\JsonException $e) {
285 continue;
286 }
287 }
288 \fclose($out);
289 break;
290 case 'diff':
291 $summary = ['total' => 0, 'passed' => 0, 'failed' => 0, 'missing' => [], 'mismatches' => []];
292 foreach (rust_anything_lines($casesPath) as $c) {
293 $summary['total']++;
294 $got = rust_anything_call($targets[$c['fn']], $c);
295 $expected = \array_intersect_key($c, ['ok' => 1, 'error' => 1, 'error_type' => 1, 'output' => 1]);
296 if (rust_anything_same($expected, $got)) {
297 $summary['passed']++;
298 } else {
299 $summary['failed']++;
300 $summary['mismatches'][] = ['fn' => $c['fn'], 'args' => $c['args'], 'expected' => $expected, 'actual' => $got];
301 }
302 }
303 \file_put_contents($outPath, \json_encode($summary, Codec::FLAGS | \JSON_INVALID_UTF8_SUBSTITUTE));
304 break;
305 case 'bench':
306 $groups = [];
307 foreach (rust_anything_lines($casesPath) as $c) {
308 $groups[$c['fn']][] = rust_anything_args($targets[$c['fn']], $c);
309 }
310 $result = [];
311 foreach ($groups as $name => $prepared) {
312 $target = $targets[$name];
313 $once = function () use ($target, $prepared) {
314 \ob_start();
315 foreach ($prepared as $args) {
316 try {
317 $target(...$args);
318 } catch (\Throwable $e) {
319 }
320 }
321 \ob_end_clean();
322 };
323 $once();
324 $passes = 0;
325 $start = \hrtime(true);
326 while (true) {
327 $once();
328 $passes++;
329 $elapsed = \hrtime(true) - $start;
330 if ($elapsed / 1e6 >= (int) $minMs) {
331 $result[$name] = ['cases' => \count($prepared), 'ns' => $elapsed / ($passes * \count($prepared))];
332 break;
333 }
334 }
335 }
336 \file_put_contents($outPath, \json_encode((object) $result, Codec::FLAGS));
337 break;
338 }
339}
340"#;