*/ private array $labels = []; public function script(Script $s, string $resFile, string $title = ''): string { $code = str_repeat("\0", 0x18) . $s->code; $entries = [$s->main]; if ($s->before) { $entries[] = $s->before; } if ($s->after) { $entries[] = $s->after; } [$ins, $labels] = (new Decoder($code, 0x18, strlen($code)))->program($entries); $this->labels = $labels; $o = []; $o[] = '// ALIS script "' . $s->name . '"' . ($title !== '' ? " — $title" : '') . ', decompiled by tools/lang (docs/language.md)'; $o[] = 'script ' . self::str($s->name); $o[] = sprintf('id 0x%04x', $s->id); $o[] = sprintf('class 0x%02x 0x%02x', $s->class1, $s->class2); $o[] = sprintf('memory 0x%04x 0x%04x 0x%04x', $s->words1, $s->vram, $s->words3); $o[] = sprintf('pack 0x%02x', $s->pack) . ($s->check !== 1 ? sprintf(' check 0x%04x', $s->check) : ''); if ($s->specs !== null) { $o[] = 'specs ' . self::hex($s->specs); } $o[] = 'resources ' . self::str($resFile); $o[] = 'main ' . self::label($s->main); if ($s->before) { $o[] = 'before ' . self::label($s->before); } if ($s->after) { $o[] = 'after ' . self::label($s->after); } $o[] = ''; $this->code = $code; $this->entries = $this->entries($ins, $code); $this->refs = []; foreach ($entries as $e) { $this->refs[$e] = ($this->refs[$e] ?? 0) + 1; } foreach ($ins as $i) { foreach (self::targets($i) as $t) { $this->refs[$t] = ($this->refs[$t] ?? 0) + 1; } } $this->index = []; foreach ($this->entries as $k => $e) { $this->index[$e['at']] = $k; } $this->consumed = []; $this->emit($o, 0, count($this->entries), 1); $endAt = strlen($code); if (isset($this->labels[$endAt]) && !isset($this->consumed[$endAt])) { $o[] = self::label($endAt) . ':'; } return implode("\n", $o) . "\n"; } /** * Each instruction of a script as its line of ALIS source (offset => text; no if / while structure: the compiled * PHP comments each of its cases with it). * @return array */ public function texts(Script $s): array { $code = str_repeat("\0", 0x18) . $s->code; [$ins, $labels] = (new Decoder($code, 0x18, strlen($code)))->program(array_values(array_filter([$s->main, $s->before, $s->after]))); $this->labels = $labels; $this->code = $code; $out = []; foreach ($ins as $at => $i) { $out[$at] = $this->instruction($i); } return $out; } private string $code = ''; /** @var list> the lines to write, in order: ['at', 'end', 'kind', 'text', ...] */ private array $entries = []; /** @var array how many jumps (and entry points) go to an offset */ private array $refs = []; /** @var array offset => index in $entries */ private array $index = []; /** @var array labels the structure says without writing them */ private array $consumed = []; /** @return list where an instruction jumps */ private static function targets(array $i): array { $t = []; $ops = $i['ops']; if (($ops[0][0] ?? '') === 'esc') { $ops = $ops[0][2]; } foreach ($ops as $op) { if ($op[0] === 'j') { $t[] = $op[2]; } elseif ($op[0] === 'sw1') { foreach ($op[4] as [, $target]) { $t[] = $target; } } elseif ($op[0] === 'sw2') { array_push($t, ...$op[5]); } } return $t; } /** The instructions as lines (ceval + cbz / cbnz fused into if / ifnot), the gaps as data. */ private function entries(array $ins, string $code): array { $out = []; $p = 0x18; $list = array_values($ins); $n = count($list); for ($k = 0; $k < $n; $k++) { $i = $list[$k]; if ($i['at'] > $p) { $lines = []; $this->data($lines, substr($code, $p, $i['at'] - $p), $p); $out[] = ['at' => $p, 'end' => $i['at'], 'kind' => 'data', 'text' => implode("\n", array_map('trim', $lines))]; } $dead = isset($i['dead']) ? ' // dead code' : ''; $next = $list[$k + 1] ?? null; $nname = $next ? Grammar::OPCODES[$next['op']][0] : ''; if ($i['op'] === 0x1f && $next && $next['at'] === $i['end'] && !isset($this->labels[$next['at']]) && preg_match('/^cbn?z(8|16|24)$/', $nname)) { $word = str_starts_with($nname, 'cbnz') ? 'if' : 'ifnot'; $cond = $this->expr($i['ops'][0][1], false); [, $bits, $target, $pad] = $next['ops'][0]; $dead = isset($next['dead']) ? ' // dead code' : $dead; $out[] = ['at' => $i['at'], 'end' => $next['end'], 'kind' => $word, 'cond' => $cond, 'target' => $target, 'canon' => $bits === 24 && !$pad && $target > $i['at'] && $dead === '', 'text' => $word . ' ' . $cond . ' ' . $this->jumpText('goto', $next, $next['ops'][0]) . $dead]; $p = $next['end']; $k++; continue; } $e = ['at' => $i['at'], 'end' => $i['end'], 'kind' => 'other', 'text' => $this->instruction($i) . $dead]; if (preg_match('/^cjmp(8|16|24)$/', Grammar::OPCODES[$i['op']][0]) && $dead === '') { [, $bits, $target, $pad] = $i['ops'][0]; $e['kind'] = 'goto'; $e['target'] = $target; $e['fwd'] = $bits === 24 && !$pad && $target > $i['at']; $e['back'] = $target <= $i['at'] && !$pad && $bits === self::canonicalBits($i['at'], $i['at'] + 1, $target); } $out[] = $e; $p = $i['end']; } if ($p < strlen($code)) { $lines = []; $this->data($lines, substr($code, $p), $p); $out[] = ['at' => $p, 'end' => strlen($code), 'kind' => 'data', 'text' => implode("\n", array_map('trim', $lines))]; } return $out; } /** Index of the line starting at $at inside ($from, $to], $to meaning the end of the region. */ private function find(int $at, int $from, int $to): ?int { $endAt = $to < count($this->entries) ? $this->entries[$to]['at'] : strlen($this->code); if ($at === $endAt) { return $to; } $k = $this->index[$at] ?? null; return $k !== null && $k > $from && $k < $to ? $k : null; } /** Writes the lines $a..$b-1, finding the if / else / while blocks the compiler made. */ private function emit(array &$o, int $a, int $b, int $depth): void { $pad = str_repeat(' ', $depth); for ($k = $a; $k < $b; $k++) { $e = $this->entries[$k]; $at = $e['at']; $block = null; if ($e['kind'] === 'ifnot' && $e['canon']) { $m = $this->find($e['target'], $k, $b); if ($m !== null) { $last = $m - 1 > $k ? $this->entries[$m - 1] : null; if ($last && $last['kind'] === 'goto' && $last['back'] && $last['target'] === $at) { $block = ['while', $m, null]; } elseif ($last && $last['kind'] === 'goto' && $last['fwd'] && $last['target'] > $e['target'] && ($m2 = $this->find($last['target'], $m - 1, $b)) !== null) { $block = ['else', $m, $m2]; } else { $block = ['if', $m, null]; } } } if ($block && $block[0] === 'while' && ($this->refs[$at] ?? 0) === 1) { $this->consumed[$at] = true; // only the loop goes back there } if (isset($this->labels[$at]) && !isset($this->consumed[$at])) { $o[] = self::label($at) . ':'; } if ($block === null) { foreach (explode("\n", $e['text']) as $j => $line) { $o[] = ($j === 0 || $e['kind'] === 'data' ? $pad : str_repeat(' ', $depth - 1)) . $line; } continue; } [$type, $m, $m2] = $block; if (($this->refs[$e['target']] ?? 0) === 1) { $this->consumed[$e['target']] = true; } $o[] = $pad . ($type === 'while' ? 'while ' : 'if ') . $e['cond'] . ' {'; if ($type === 'while') { $this->emit($o, $k + 1, $m - 1, $depth + 1); if (isset($this->labels[$this->entries[$m - 1]['at']])) { $o[] = self::label($this->entries[$m - 1]['at']) . ':'; // a jump to the goto that "}" makes } $o[] = $pad . '}'; $k = $m - 1; continue; } if ($type === 'if') { $this->emit($o, $k + 1, $m, $depth + 1); $o[] = $pad . '}'; $k = $m - 1; continue; } $this->emit($o, $k + 1, $m - 1, $depth + 1); $l2 = $this->entries[$m - 1]['target']; if (($this->refs[$l2] ?? 0) === 1) { $this->consumed[$l2] = true; } if (isset($this->labels[$this->entries[$m - 1]['at']])) { $o[] = self::label($this->entries[$m - 1]['at']) . ':'; // a jump to the goto that "} else {" makes } $o[] = $pad . '} else {'; $this->emit($o, $m, $m2, $depth + 1); $o[] = $pad . '}'; $k = $m2 - 1; } } private function data(array &$o, string $bytes, int $at): void { foreach (str_split($bytes, 32) as $chunk) { $o[] = ' data ' . self::hex($chunk); } } public static function label(int $at): string { return sprintf('L%04x', $at); } public static function hex(string $b): string { return 'hex"' . bin2hex($b) . '"'; } /** A string literal: printable ASCII as is, bytes 0x80..0xfe as their code page 437 letter, the rest as \xNN. */ public static function str(string $s): string { $out = '"'; $len = strlen($s); for ($i = 0; $i < $len; $i++) { $c = ord($s[$i]); $out .= match (true) { $s[$i] === '"' => '\\"', $s[$i] === '\\' => '\\\\', $c >= 0x20 && $c < 0x7f => $s[$i], $c >= 0x80 && $c !== 0xff => Names::cp437()[$c], default => sprintf('\\x%02x', $c), }; } return $out . '"'; } private function instruction(array $i): string { $name = Grammar::OPCODES[$i['op']][0]; $ops = $i['ops']; switch ($name) { case 'cstore': return $this->target($ops[1][1], Grammar::STORES) . ' = ' . $this->expr($ops[0][1], false); case 'cadd': case 'csub': return $this->target($ops[1][1], Grammar::ADDS) . ($name === 'cadd' ? ' += ' : ' -= ') . $this->expr($ops[0][1], false); case 'cjmp8': case 'cjmp16': case 'cjmp24': return $this->jumpText('goto', $i, $ops[0]); case 'cjsr8': case 'cjsr16': case 'cjsr24': return $this->jumpText('call', $i, $ops[0]); case 'cstart8': case 'cstart16': case 'cstart24': return $this->jumpText('start', $i, $ops[0]); case 'cbz8': case 'cbz16': case 'cbz24': return 'ifz ' . $this->jumpText('goto', $i, $ops[0]); case 'cbnz8': case 'cbnz16': case 'cbnz24': return 'ifnz ' . $this->jumpText('goto', $i, $ops[0]); case 'cbeq8': case 'cbeq16': case 'cbeq24': return 'ifeq ' . $this->jumpText('goto', $i, $ops[0]); case 'cbne8': case 'cbne16': case 'cbne24': return 'ifne ' . $this->jumpText('goto', $i, $ops[0]); case 'cloop8': case 'cloop16': case 'cloop24': return 'loop ' . $this->target($ops[1][1], Grammar::ADDS) . ' ' . $this->jumpText('goto', $i, $ops[0]); case 'cesc1': [, $code, $eops] = $ops[0]; $ename = Grammar::ESC1[$code][0]; return ($code === 0 ? 'esc1 nul' : substr($ename, 1)) . ($eops ? ' ' . $this->operands($eops) : ''); } $word = Names::statement($name); if (!$ops) { return $word; } $sp = $ops[0]; switch ($sp[0]) { case 'dim': [, $off, $counter, $byte2, $vals] = $sp; return sprintf('dim %s, 0x%02x, 0x%02x, [%s]', self::off($off), $counter, $byte2, implode(', ', $vals)); case 'sw1': [, $e, , $pad, $cases] = $sp; $t = 'switch ' . $this->expr($e, false) . self::padText($pad); foreach ($cases as [$test, $target]) { $t .= "\n case $test goto " . self::label($target); } return $t . "\n end"; case 'sw2': [, $e, , $pad, $base, $targets] = $sp; $t = 'table ' . $this->expr($e, false) . ', ' . $base . self::padText($pad); foreach ($targets as $target) { $t .= "\n goto " . self::label($target); } return $t . "\n end"; case 'load': [, $id, $file, $e] = $sp; return $file !== null ? "load $id, " . self::str($file) : 'load ' . $this->expr($e, false); case 'fopen': [, $file, $a, $b] = $sp; return $file !== null ? 'fopen z' . self::str($file) . ", $a" : 'fopen ' . $this->expr($a, false) . ', ' . $this->expr($b, false); case 'send': [, , $to, $vals] = $sp; return 'send ' . $this->expr($to, false) . ', ' . implode(', ', array_map(fn ($v) => $this->expr($v, false), $vals)); case 'defvect': return 'defvect ' . self::hex($sp[2]); } return $word . ' ' . $this->operands($ops); } private static function padText(?int $pad): string { return $pad !== null && $pad !== 0 ? " pad $pad" : ''; } private function operands(array $ops): string { $t = []; foreach ($ops as $op) { $t[] = match ($op[0]) { 'E' => $this->expr($op[1], false), 'S' => $this->target($op[1], Grammar::STORES), 'A' => $this->target($op[1], Grammar::ADDS), 'b', 'w', 'W', 'l' => (string) $op[1], 'z' => self::str($op[1]), 'v' => '&' . ($op[2] ? 'm' : 'v') . '[' . self::off($op[1]) . ']', 'r' => self::hex($op[1]), default => throw new \LogicException('operand ' . $op[0]), }; } return implode(', ', $t); } /** "goto L1234", with the size when it is not the compiler's (forward: 24, backward: the shortest). */ private function jumpText(string $word, array $i, array $j): string { [, $bits, $target, $pad] = $j; $name = Grammar::OPCODES[$i['op']][0]; // where the offset starts: after the opcode (cloop too: its offset comes before its target variable) $opEnd = $i['at'] + 1; $canon = self::canonicalBits($i['at'], $opEnd, $target); $t = $word; if ($bits !== $canon || ($pad ?? 0) !== 0) { $t .= '.' . $bits . (($pad ?? 0) !== 0 ? '/' . $pad : ''); } unset($name); return $t . ' ' . self::label($target); } /** The jump size the original compiler chose: forward 24 bits, backward the shortest that fits. */ public static function canonicalBits(int $at, int $operandAt, int $target): int { if ($target > $at) { return 24; } $d = $target - ($operandAt + 1); return $d >= -128 ? 8 : 16; } public static function off(int $o): string { return $o < 0 ? sprintf('-0x%x', -$o) : sprintf('0x%x', $o); } /** An item standing alone (a binary operator's right operand, the start of a chain). */ private function item(array $it, array $table = Grammar::OPERS): string { [$name, $spec, $kind] = $table[$it['c']]; switch ($kind) { case 'v': case 't': if ($name === 'oimmp') { return self::str($it['a']); } if ($spec === 'i8' || $spec === 'i16' || $spec === 'i32') { $canon = $it['a'] >= -128 && $it['a'] <= 127 ? 'i8' : ($it['a'] >= -32768 && $it['a'] <= 32767 ? 'i16' : 'i32'); return $it['a'] . ($spec !== $canon ? ':' . substr($spec, 1) : ''); } return $this->varText($name, $spec, $it['a']) . ($kind === 't' ? '()' : ''); case 'f': return Names::FUNCS[$name] . '()'; case 'e': return '(' . $this->chain(array_slice($it['sub'], 0, -1), true) . ')'; case 'b': return Names::BINOPS[$name] . ' ' . $this->item($it['sub'][0]); case 'x': return 'fin()'; } throw new \LogicException("item kind $kind"); } private function varText(string $name, string $spec, int|array $a): string { [$prefix, $mode] = Names::variable($name); if ($spec === 'h') { return $prefix . '[' . self::off($a[0]) . ', ' . self::off($a[1]) . ']'; } $hint = $mode === 'loc' && $a >= 0 && $a <= 255 ? ':loc' : ''; return $prefix . $hint . '[' . self::off($a) . ']'; } /** The top-level expression of an operand. */ private function expr(array $it, bool $inParens): string { if ($it['c'] === 0x38) { $chain = array_slice($it['sub'], 0, -1); if (count($chain) >= 2) { return $this->chain($chain, $inParens); } } return $this->item($it); } /** A list of items evaluated left to right (the content of an oeval). */ private function chain(array $items, bool $inParens): string { // a stack of the values pushed: "A ; push ; B op pile()" is how the compiler wrote A op (B): "A op [B]" $sep = $inParens ? ', ' : ' ; push ; '; $stack = []; $cur = ''; foreach ($items as $k => $it) { [$name, , $kind] = Grammar::OPERS[$it['c']]; if ($kind === 'b') { $rhs = $it['sub'][0]; if ($rhs['c'] === 0x36 && $stack) { $left = array_pop($stack); $cur = ($left === '' ? '' : $left . ' ') . Names::BINOPS[$name] . ' [' . $cur . ']'; } else { $cur .= ($cur === '' ? '' : ' ') . Names::BINOPS[$name] . ' ' . $this->item($rhs); } } elseif ($name === 'opushacc') { $stack[] = $cur; $cur = ''; } elseif (($kind === 'f' && !in_array($name, Names::VALUES, true)) || $kind === 't') { $text = $kind === 'f' ? Names::FUNCS[$name] : $this->varText($name, Grammar::OPERS[$it['c']][1], $it['a']); $cur = $text . '(' . ($k === 0 ? '' : $this->chain(array_slice($items, 0, $k), true)) . ')'; $stack = []; } else { $cur .= ($cur === '' ? '' : ' ; ') . $this->item($it); } } return implode($sep, [...$stack, $cur]); } /** A store / add target. */ private function target(array $it, array $table): string { [$name, $spec, $kind] = $table[$it['c']]; if ($kind === 's') { $chain = array_slice($it['sub'], 0, -2); $last = end($it['sub']); return $this->target($last, $table) . '(' . $this->chain($chain, true) . ')'; } if ($kind === 'f' || $kind === 'x') { return Names::FUNCS[$name]; } return $this->varText($name, $spec, $it['a']); } }