run.php (3143B)
1 #!/usr/bin/env php 2 <?php 3 4 declare(strict_types=1); 5 6 /** 7 * run.php — Arboricx PHP host shell via libarboricx C ABI. 8 * 9 * Usage: 10 * php run.php run <bundle.arboricx> [args...] 11 * php run.php inspect <bundle.arboricx> 12 */ 13 14 require __DIR__ . '/src/common.php'; 15 16 use function Arboricx\{ctx_init, ctx_free, loadBundleDefault, ofNumber, ofString, app, reduce, toString, toBool, toNumber, findLib, decode, decodeType, readBundle}; 17 18 // ── Commands ───────────────────────────────────────────────────────────────── 19 20 function bail(string $msg): void 21 { 22 fwrite(STDERR, "Error: $msg\n"); 23 exit(1); 24 } 25 26 function cmdRun(string $libPath, string $bundlePath, array $args): void 27 { 28 $ctx = ctx_init($libPath); 29 try { 30 $term = loadBundleDefault($ctx, readBundle($bundlePath)); 31 32 foreach ($args as $arg) { 33 $argTree = preg_match('/^\d+$/', $arg) ? ofNumber($ctx, (int)$arg) : ofString($ctx, $arg); 34 $term = app($ctx, $term, $argTree); 35 } 36 37 $result = reduce($ctx, $term, 1_000_000_000); 38 echo decode($ctx, $result) . "\n"; 39 } catch (\Throwable $e) { 40 bail($e->getMessage()); 41 } finally { 42 ctx_free($ctx); 43 } 44 } 45 46 function cmdInspect(string $libPath, string $bundlePath): void 47 { 48 $ctx = ctx_init($libPath); 49 try { 50 $bundle = readBundle($bundlePath); 51 echo "Bundle: $bundlePath\nSize: " . strlen($bundle) . " bytes\n\nResult:\n"; 52 53 $term = loadBundleDefault($ctx, $bundle); 54 $result = reduce($ctx, $term, 1_000_000_000); 55 56 $type = decodeType($ctx, $result); 57 try { 58 $value = decode($ctx, $result); 59 } catch (\RuntimeException $e) { 60 $value = '(raw tree)'; 61 } 62 echo " Type: $type\n Value: $value\n"; 63 } catch (\Throwable $e) { 64 bail($e->getMessage()); 65 } finally { 66 ctx_free($ctx); 67 } 68 } 69 70 // ── Main ───────────────────────────────────────────────────────────────────── 71 72 $argv = $_SERVER['argv'] ?? []; 73 $argc = $_SERVER['argc'] ?? 0; 74 75 if ($argc < 2) { 76 echo "Arboricx PHP Host Shell (via libarboricx C ABI)\n\nUsage:\n"; 77 echo " php run.php run <bundle.arboricx> [args...]\n"; 78 echo " php run.php inspect <bundle.arboricx>\n"; 79 exit(0); 80 } 81 82 $libPath = findLib(); 83 $command = $argv[1]; 84 85 switch ($command) { 86 case 'run': 87 if ($argc < 3) { 88 fwrite(STDERR, "Usage: php run.php run <bundle.arboricx> [args...]\n"); 89 exit(1); 90 } 91 cmdRun($libPath, $argv[2], array_slice($argv, 3)); 92 break; 93 case 'inspect': 94 if ($argc < 3) { 95 fwrite(STDERR, "Usage: php run.php inspect <bundle.arboricx>\n"); 96 exit(1); 97 } 98 cmdInspect($libPath, $argv[2]); 99 break; 100 default: 101 fwrite(STDERR, "Unknown command: $command\nUsage: php run.php run|inspect ...\n"); 102 exit(1); 103 }