Skip to main content

rust_anything/
codegen_php.rs

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    $classmapPath = \getenv('RUST_ANYTHING_PHP_CLASSMAP');
203    if ($classmapPath !== false && $classmapPath !== '') {
204        $classmap = \json_decode(\file_get_contents($classmapPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
205        \spl_autoload_register(static function (string $name) use ($classmap): void {
206            $file = $classmap[\strtolower($name)] ?? null;
207            if ($file !== null) {
208                require_once $file;
209            }
210        });
211    }
212    foreach (\array_slice($argv, 6) as $file) {
213        require_once $file;
214    }
215    $targets = \json_decode(\file_get_contents($targetsPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
216
217    function rust_anything_args(string $target, array $c): array
218    {
219        $args = $c['args'] ?? [];
220        while ($args && \is_array(\end($args)) && \array_key_exists('$undefined', \end($args))) {
221            \array_pop($args);
222        }
223        $params = null;
224        $out = [];
225        $named = false;
226        foreach (\array_values($args) as $i => $arg) {
227            if (\is_array($arg) && \count($arg) === 1 && \array_key_exists('$undefined', $arg)) {
228                $named = true;
229                continue;
230            }
231            if ($named) {
232                $params ??= (new \ReflectionFunction($target))->getParameters();
233                $out[isset($params[$i]) ? $params[$i]->getName() : $i] = Codec::dec($arg);
234            } else {
235                $out[] = Codec::dec($arg);
236            }
237        }
238        return $out;
239    }
240
241    function rust_anything_call(string $target, array $c): array
242    {
243        \ob_start();
244        try {
245            $result = ['ok' => Codec::enc($target(...rust_anything_args($target, $c)))];
246        } catch (\Throwable $e) {
247            $result = ['error' => $e->getMessage(), 'error_type' => \get_class($e)];
248        } finally {
249            $output = \ob_get_clean();
250        }
251        if (\is_string($output) && $output !== '') {
252            $result['output'] = $output;
253        }
254        return $result;
255    }
256
257    function rust_anything_lines(string $path): array
258    {
259        $out = [];
260        foreach (\file($path, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES) as $line) {
261            $out[] = \json_decode($line, true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
262        }
263        return $out;
264    }
265
266    function rust_anything_same(array $expected, array $got): bool
267    {
268        if (\str_starts_with((string) ($got['error'] ?? ''), 'Rust panic:')) {
269            return false;
270        }
271        if (($expected['output'] ?? '') !== ($got['output'] ?? '')) {
272            return false;
273        }
274        if (\array_key_exists('error', $expected)) {
275            return \array_key_exists('error', $got) && $expected['error_type'] === $got['error_type'];
276        }
277        return !\array_key_exists('error', $got)
278            && \json_encode($expected['ok'], Codec::FLAGS) === \json_encode($got['ok'], Codec::FLAGS);
279    }
280
281    switch ($mode) {
282        case 'record':
283            $progress = \getenv('RUST_ANYTHING_PROGRESS');
284            $out = \fopen($outPath, 'w');
285            $cases = \json_decode(\file_get_contents($casesPath), true, Codec::DEPTH, \JSON_THROW_ON_ERROR);
286            foreach ($cases as $index => $c) {
287                if ($progress !== false && $progress !== '') {
288                    \file_put_contents($progress, "$index\n", \FILE_APPEND);
289                }
290                $line = ['fn' => $c['fn'], 'args' => $c['args'] ?? []] + rust_anything_call($targets[$c['fn']], $c);
291                try {
292                    \fwrite($out, \json_encode($line, Codec::FLAGS) . "\n");
293                    \fflush($out);
294                } catch (\JsonException $e) {
295                    continue;
296                }
297            }
298            \fclose($out);
299            break;
300        case 'diff':
301            $summary = ['total' => 0, 'passed' => 0, 'failed' => 0, 'missing' => [], 'mismatches' => []];
302            foreach (rust_anything_lines($casesPath) as $c) {
303                $summary['total']++;
304                $got = rust_anything_call($targets[$c['fn']], $c);
305                $expected = \array_intersect_key($c, ['ok' => 1, 'error' => 1, 'error_type' => 1, 'output' => 1]);
306                if (rust_anything_same($expected, $got)) {
307                    $summary['passed']++;
308                } else {
309                    $summary['failed']++;
310                    $summary['mismatches'][] = ['fn' => $c['fn'], 'args' => $c['args'], 'expected' => $expected, 'actual' => $got];
311                }
312            }
313            \file_put_contents($outPath, \json_encode($summary, Codec::FLAGS | \JSON_INVALID_UTF8_SUBSTITUTE));
314            break;
315        case 'bench':
316            $groups = [];
317            foreach (rust_anything_lines($casesPath) as $c) {
318                $groups[$c['fn']][] = rust_anything_args($targets[$c['fn']], $c);
319            }
320            $result = [];
321            foreach ($groups as $name => $prepared) {
322                $target = $targets[$name];
323                $once = function () use ($target, $prepared) {
324                    \ob_start();
325                    foreach ($prepared as $args) {
326                        try {
327                            $target(...$args);
328                        } catch (\Throwable $e) {
329                        }
330                    }
331                    \ob_end_clean();
332                };
333                $once();
334                $passes = 0;
335                $start = \hrtime(true);
336                while (true) {
337                    $once();
338                    $passes++;
339                    $elapsed = \hrtime(true) - $start;
340                    if ($elapsed / 1e6 >= (int) $minMs) {
341                        $result[$name] = ['cases' => \count($prepared), 'ns' => $elapsed / ($passes * \count($prepared))];
342                        break;
343                    }
344                }
345            }
346            \file_put_contents($outPath, \json_encode((object) $result, Codec::FLAGS));
347            break;
348    }
349}
350"#;