<?php// Decompiles the scripts (.io) of a game into ALIS source: <out>/<name>.als + <name>.res (the resources), then// compiles each one back and checks that the bytes are the same.// bin/jumphp php games/alis tools/lang/decompile.php ../../.alis-data/robinson ../../.alis-data/robinson/srcuse App\Alis\Lang\Assembler;use App\Alis\Lang\Printer;use App\Alis\Lang\Script;use App\Alis\Machine;use App\Alis\UnpackVars;require __DIR__ . '/../../vendor/autoload.php';$base = __DIR__ . '/../../';$dir = rtrim($argv[1] ?? 'data/robinson', '/');$out = rtrim($argv[2] ?? "$dir/src", '/');$dir = str_starts_with($dir, '/') ? $dir : $base . $dir;$out = str_starts_with($out, '/') ? $out : $base . $out;@mkdir($out, 0777, true);$m = new Machine();if (!$m->boot($dir)) { fwrite(STDERR, "boot failed: {$m->error}\n"); exit(1);}$title = $m->gameName;$ok = $bad = $data = 0;$lines = 0;foreach (glob("$dir/*.[iI][oO]") as $path) { $raw = file_get_contents($path); $magic = unpack('V', $raw)[1]; $check = unpack('v', substr($raw, 4, 2))[1]; $isMain = $check === 0; $pack = ($magic >> 24) & 0xff; $name = strtolower(basename($path, '.' . pathinfo($path, PATHINFO_EXTENSION))); if ($pack & 0x80) { $size = ($magic & 0xffffff) - UnpackVars::$kPackedHeaderSize - ($isMain ? UnpackVars::$kVMSpecsSize : 0); \App\Alis\Alis::$typepack = \App\Alis\s8($pack & 0xfe); $buf = \App\Alis\script_scratch(1024 + $size); $bytes = \App\Alis\mem_read($buf, \App\Alis\unpack_script($path, $buf)); } else { $bytes = substr($raw, 6 + ($isMain ? 16 : 0)); } if (!Script::isScript($bytes)) { $data++; echo "$name: not a script, the game keeps $name.io\n"; continue; } $s = Script::fromBytes($name, $bytes, $pack, $check, $isMain ? substr($raw, 6, 16) : null); $src = (new Printer())->script($s, "$name.res", $title); file_put_contents("$out/$name.als", $src); file_put_contents("$out/$name.res", $s->resources); $lines += substr_count($src, "\n"); try { $back = (new Assembler())->compile($src, fn (string $f) => file_get_contents("$out/$f")); } catch (\App\Alis\Lang\CompileError $e) { $bad++; echo "$name: ", $e->getMessage(), "\n"; continue; } if ($back->bytes() === $bytes && $back->pack === $pack && $back->check === $check) { $ok++; } else { $bad++; echo "$name: compiles to different bytes\n"; }}printf("%d scripts decompiled (%d lines) and compiled back to the same bytes, %d different, %d data files\n", $ok, $lines, $bad, $data);exit($bad ? 1 : 0);