ES
games/alis / src / Alis / Lang / Assembler.php · commit 9c722cf
<?phpnamespace App\Alis\Lang;/** * Compiles ALIS source (docs/language.md, what Printer writes) into a Script: the bytes the VM runs. * One pass like the original compiler: a backward jump takes the shortest size that fits, a forward one 24 bits * (the target is not known yet), constants and variable offsets the shortest form; labels are fixed up at the end. */final class Assembler{    private string $out = '';    /** @var array<string, int> */    private array $labels = [];    /** @var list<array{0: int, 1: int, 2: int, 3: string, 4: int}> [where, bytes, base, label, line] */    private array $fixups = [];    private int $line = 0;    /** @var list<array{0: string, 1: string, 2: string, 3: int}> open blocks: [if|else|while, label, label, line] */    private array $blocks = [];    private int $blockSeq = 0;    /** @var list<array{0: string, 1: string}> tokens of the current line */    private array $t = [];    private int $k = 0;    /** @var array<string, int> statement word => opcode */    private static array $words = [];    /** @var array<string, array<string, int>> table => name => code */    private static array $codes = [];    /**     * @param callable(string): string $readFile reads a file named in the source (the resources)     */    public function compile(string $source, callable $readFile): Script    {        self::init();        $s = new Script();        $this->out = str_repeat("\0", 0x18);        $this->labels = [];        $this->fixups = [];        $this->blocks = [];        $entries = [];        $lines = preg_split('/\r?\n/', $source);        $n = count($lines);        for ($this->line = 1; $this->line <= $n; $this->line++) {            $text = $lines[$this->line - 1];            $this->tokenize($text);            if (!$this->t) {                continue;            }            // labels            while (count($this->t) >= 2 && $this->t[0][0] === 'id' && $this->t[1][1] === ':' && $this->t[1][0] === 'op') {                $name = $this->t[0][1];                if (isset($this->labels[$name])) {                    $this->fail("label $name defined twice");                }                $this->labels[$name] = strlen($this->out);                array_splice($this->t, 0, 2);            }            if (!$this->t) {                continue;            }            $this->k = 0;            $word = $this->t[0][1];            if ($this->t[0][0] === 'id' && in_array($word, ['script', 'id', 'class', 'memory', 'pack', 'specs', 'resources', 'main', 'before', 'after'], true)) {                $this->k = 1;                switch ($word) {                    case 'script': $s->name = $this->string(); break;                    case 'id': $s->id = $this->number(); break;                    case 'class': $s->class1 = $this->number(); $s->class2 = $this->number(); break;                    case 'memory': $s->words1 = $this->number(); $s->vram = $this->number(); $s->words3 = $this->number(); break;                    case 'pack':                        $s->pack = $this->number();                        if ($this->peekIs('check')) {                            $this->k++;                            $s->check = $this->number();                        }                        break;                    case 'specs': $s->specs = $this->hexBlob(); break;                    case 'resources': $s->resources = $readFile($this->string()); break;                    default: $entries[$word] = [$this->ident(), $this->line]; break;                }                $this->end();                continue;            }            // switch / table blocks take the following lines up to "end"            if ($word === 'switch' || $word === 'table') {                $block = [];                while (++$this->line <= $n) {                    $l = trim(preg_replace('#//.*$#', '', $lines[$this->line - 1]));                    if ($l === 'end') {                        break;                    }                    if ($l !== '') {                        $block[] = [$l, $this->line];                    }                }                $this->tokenize($text);                $this->k = 0;                $this->switchBlock($block);                continue;            }            if ($this->t[0] === ['op', '}']) {                $this->closeBlock();                continue;            }            $this->statement();            $this->end();        }        if ($this->blocks) {            $this->line = end($this->blocks)[3];            $this->fail('this block has no }');        }        foreach ($this->fixups as [$at, $bytes, $base, $label, $line]) {            if (!isset($this->labels[$label])) {                $this->line = $line;                $this->fail("unknown label $label");            }            $off = $this->labels[$label] - $base;            if ($bytes === 1 ? ($off < -128 || $off > 127) : ($off < -32768 || $off > 32767)) {                $this->line = $line;                $this->fail("jump to $label is too far for its size");            }            $this->out = substr_replace($this->out, $bytes === 1 ? chr($off & 0xff) : pack('v', $off & 0xffff), $at, $bytes);        }        foreach (['main', 'before', 'after'] as $e) {            if (isset($entries[$e])) {                [$label, $line] = $entries[$e];                if (!isset($this->labels[$label])) {                    $this->line = $line;                    $this->fail("unknown label $label");                }                $s->$e = $this->labels[$label];            }        }        $s->code = substr($this->out, 0x18);        return $s;    }    private static function init(): void    {        if (self::$words) {            return;        }        foreach (Grammar::OPCODES as $code => [$name]) {            self::$words[Names::statement($name)] = $code;        }        foreach (['O' => Grammar::OPERS, 'S' => Grammar::STORES, 'A' => Grammar::ADDS] as $t => $table) {            foreach ($table as $code => [$name]) {                self::$codes[$t][$name] ??= $code;            }        }    }    // --- statements -------------------------------------------------------------------------------------------    private function statement(): void    {        $word = $this->t[0][1];        $isId = $this->t[0][0] === 'id';        // assignments: target = / += / -= expression        $eq = $this->findTop(['=', '+=', '-=']);        if ($eq !== null) {            $op = $this->t[$eq][1];            $table = $op === '=' ? 'S' : 'A';            $target = $this->target($table);            if ($this->k !== $eq) {                $this->fail('unexpected ' . $this->t[$this->k][1] . ' in the target');            }            $this->k++;            $e = $this->expression();            $this->emit(chr($op === '=' ? 0x1e : ($op === '+=' ? 0x20 : 0x21)));            $this->emitItem($e, 'O');            $this->emitItem($target, $table);            return;        }        if (!$isId) {            $this->fail("unexpected $word");        }        $this->k = 1;        [$base, $size, $pad] = $this->sizedWord($word);        switch ($base) {            case 'goto': $this->jump([8 => 0x08, 16 => 0x09, 24 => 0x0a], $size, $pad); return;            case 'call': $this->jump([8 => 0x05, 16 => 0x06, 24 => 0x07], $size, $pad); return;            case 'start': $this->jump([8 => 0x30, 16 => 0x31, 24 => 0x32], $size, $pad); return;            case 'ifz':            case 'ifnz':            case 'ifeq':            case 'ifne':                $ops = ['ifz' => [0x12, 0x13, 0x14], 'ifnz' => [0x15, 0x16, 0x17], 'ifeq' => [0x18, 0x19, 0x1a], 'ifne' => [0x1b, 0x1c, 0x1d]][$base];                [$gword, $gsize, $gpad] = $this->sizedWord($this->ident());                if ($gword !== 'goto') {                    $this->fail("$base goto <label>");                }                $this->jump([8 => $ops[0], 16 => $ops[1], 24 => $ops[2]], $gsize, $gpad);                return;            case 'while':            case 'if':            case 'ifnot':                $top = $this->newLabel();                $this->labels[$top] = strlen($this->out);                $e = $this->expression(true);                if ($base !== 'ifnot' && $this->peekIs('{')) {                    // if C { ... } [else { ... }] / while C { ... }: ceval C, cbz24 to the end of the block                    $this->k++;                    $end = $this->newLabel();                    $this->emit("\x1f");                    $this->emitItem($e, 'O');                    $this->jump([24 => 0x14], 24, 0, $end);                    $this->blocks[] = [$base, $end, $top, $this->line];                    return;                }                if ($base === 'while') {                    $this->fail('while <expression> {');                }                [$gword, $gsize, $gpad] = $this->sizedWord($this->ident());                if ($gword !== 'goto') {                    $this->fail("$base <expression> goto <label>");                }                $this->emit("\x1f");                $this->emitItem($e, 'O');                $this->jump($base === 'if' ? [8 => 0x15, 16 => 0x16, 24 => 0x17] : [8 => 0x12, 16 => 0x13, 24 => 0x14], $gsize, $gpad);                return;            case 'loop':                $target = $this->target('A');                [$gword, $gsize, $gpad] = $this->sizedWord($this->ident());                if ($gword !== 'goto') {                    $this->fail('loop <variable> goto <label>');                }                $at = strlen($this->out);                $label = $this->ident();                $bits = $gsize ?: $this->canonicalBits($at, $label);                $this->emit(chr([8 => 0x2b, 16 => 0x2c, 24 => 0x2d][$bits]));                $this->jumpOperand($bits, $label, $gpad);                $this->emitItem($target, 'A');                return;            case 'esc1':                $this->expect('nul');                $this->emit("\x01\x00");                return;            case 'dim':                $off = $this->number();                $this->comma();                $counter = $this->number();                $this->comma();                $byte2 = $this->number();                $this->comma();                $this->expect('[');                $vals = [];                while (!$this->peekIs(']')) {                    $vals[] = $this->number();                    if ($this->peekIs(',')) {                        $this->k++;                    }                }                $this->k++;                if (count($vals) !== ($counter & 0xf) + 1) {                    $this->fail('dim: ' . (($counter & 0xf) + 1) . ' values expected');                }                $b = "\x29" . pack('vCC', $off & 0xffff, $counter, $byte2);                foreach ($vals as $i => $v) {                    $b .= $i < count($vals) - 1 && !($counter & 0x80) ? pack('v', $v & 0xffff) : pack('V', $v);                }                $this->emit($b);                return;            case 'load':                if ($this->t[$this->k][0] === 'num') {                    $id = $this->number();                    $this->comma();                    $this->emit("\x45" . pack('v', $id) . $this->string() . "\0");                    return;                }                $this->emit("\x45\x00\x00");                $this->emitItem($this->expression(), 'O');                return;            case 'fopen':                if ($this->t[$this->k][0] === 'zstr') {                    $file = $this->t[$this->k++][1];                    $this->comma();                    $this->emit("\x70" . $file . "\0" . pack('v', $this->number()));                    return;                }                $this->emit("\x70\xff");                $this->emitItem($this->expression(), 'O');                $this->comma();                $this->emitItem($this->expression(), 'O');                return;            case 'send':                $items = [$this->expression()];                while ($this->peekIs(',')) {                    $this->k++;                    $items[] = $this->expression();                }                if (count($items) < 2) {                    $this->fail('send <entity>, <value>...');                }                $this->emit("\x61" . chr(count($items) - 2));                foreach ($items as $it) {                    $this->emitItem($it, 'O');                }                return;            case 'defvect':                $blob = $this->hexBlob();                if (strlen($blob) < 3 || strlen($blob) % 3 !== 0) {                    $this->fail('defvect: 3 bytes per vector, plus 3');                }                $this->emit("\x89" . chr(intdiv(strlen($blob), 3) - 1) . $blob);                return;            case 'data':                $this->emit($this->hexBlob());                return;        }        // escape 1 statements (soundon, openfilm...)        foreach (Grammar::ESC1 as $code => [$ename, $spec]) {            if ($code > 0 && substr($ename, 1) === $word) {                $this->emit("\x01" . chr($code));                $this->operands($spec);                return;            }        }        if (!isset(self::$words[$word])) {            $this->fail("unknown statement $word");        }        $op = self::$words[$word];        $spec = Grammar::OPCODES[$op][1];        $this->emit(chr($op));        if ($spec === '@zap') {            $n = 0;            do {                if ($n > 0) {                    $this->comma();                }                $this->emitItem($this->expression(), 'O');                $n++;            } while ($this->peekIs(','));            if ($n !== 4 && $n !== 5) {                $this->fail('zap: 4 or 5 operands');            }            return;        }        if ($spec === '@chartmap') {            $this->vaddr();            $this->comma();            $this->emitItem($this->expression(), 'O');            $this->comma();            if ($this->peekIs('&')) {                $this->vaddr();            } else {                $this->emitItem($this->expression(), 'O');            }            return;        }        if ($spec !== '' && $spec[0] === '@') {            $this->fail("$word has its own syntax");        }        $this->operands($spec);    }    private function operands(string $spec): void    {        if ($spec === '') {            return;        }        foreach (explode(' ', $spec) as $i => $tok) {            if ($i > 0) {                $this->comma();            }            switch ($tok) {                case 'E': $this->emitItem($this->expression(), 'O'); break;                case 'S': $this->emitItem($this->target('S'), 'S'); break;                case 'A': $this->emitItem($this->target('A'), 'A'); break;                case 'b': $this->emit(chr($this->number() & 0xff)); break;                case 'w':                case 'W': $this->emit(pack('v', $this->number() & 0xffff)); break;                case 'l': $this->emit(pack('V', $this->number())); break;                case 'z': $this->emit($this->string() . "\0"); break;                case 'v': $this->vaddr(); break;                default:                    if ($tok[0] === 'r') {                        $blob = $this->hexBlob();                        if (strlen($blob) !== (int) substr($tok, 1)) {                            $this->fail(substr($tok, 1) . ' bytes expected');                        }                        $this->emit($blob);                        break;                    }                    throw new \LogicException("operand $tok");            }        }    }    private function vaddr(): void    {        $this->expect('&');        $p = $this->ident();        $this->expect('[');        $off = $this->number();        $this->expect(']');        if ($p === 'm') {            $this->emit(pack('vv', 0, $off & 0xffff));        } elseif ($p === 'v') {            if ($off === 0) {                $this->fail('&v[0] cannot be written (0 means "main")');            }            $this->emit(pack('v', $off & 0xffff));        } else {            $this->fail('&v[...] or &m[...]');        }    }    private function newLabel(): string    {        return "\0block" . (++$this->blockSeq);    }    /** "}" ends a block, "} else {" starts the else part of an if. */    private function closeBlock(): void    {        if (!$this->blocks) {            $this->fail('} without a block');        }        [$type, $end, $top, $line] = array_pop($this->blocks);        if (count($this->t) === 3 && $this->t[1] === ['id', 'else'] && $this->t[2] === ['op', '{']) {            if ($type !== 'if') {                $this->fail('else after a ' . $type);            }            $after = $this->newLabel();            $this->jump([24 => 0x0a], 24, 0, $after);            $this->labels[$end] = strlen($this->out);            $this->blocks[] = ['else', $after, $top, $line];            return;        }        if (count($this->t) !== 1) {            $this->fail('} or } else {');        }        if ($type === 'while') {            $this->jump([8 => 0x08, 16 => 0x09, 24 => 0x0a], 0, 0, $top);        }        $this->labels[$end] = strlen($this->out);    }    /** "goto.16/3" => ['goto', 16, 3] */    private function sizedWord(string $word): array    {        if (preg_match('/^(\w+)\.(8|16|24)(?:\/(\d+))?$/', $word, $m)) {            return [$m[1], (int) $m[2], (int) ($m[3] ?? 0)];        }        return [$word, 0, 0];    }    private function jump(array $opcodes, int $size, int $pad, ?string $label = null): void    {        $at = strlen($this->out);        $label ??= $this->ident();        $bits = $size ?: $this->canonicalBits($at, $label);        $this->emit(chr($opcodes[$bits]));        $this->jumpOperand($bits, $label, $pad);    }    private function canonicalBits(int $at, string $label): int    {        if (!isset($this->labels[$label])) {            return 24;        }        $d = $this->labels[$label] - ($at + 2);        return $d >= -128 ? 8 : 16;    }    private function jumpOperand(int $bits, string $label, int $pad): void    {        $at = strlen($this->out);        if ($bits === 8) {            $this->fixups[] = [$at, 1, $at + 1, $label, $this->line];            $this->emit("\0");        } elseif ($bits === 16) {            $this->fixups[] = [$at, 2, $at + 2, $label, $this->line];            $this->emit("\0\0");        } else {            $this->fixups[] = [$at, 2, $at + 3, $label, $this->line];            $this->emit("\0\0" . chr($pad));        }    }    /** @param list<array{0: string, 1: int}> $block */    private function switchBlock(array $block): void    {        $word = $this->t[0][1];        $this->k = 1;        $e = $this->expression(true);        $base = 0;        if ($word === 'table') {            $this->comma();            $base = $this->number();        }        $pad = 0;        if ($this->peekIs('pad')) {            $this->k++;            $pad = $this->number();        }        $this->end();        $line = $this->line;        $entries = [];        foreach ($block as [$text, $l]) {            $this->line = $l;            $this->tokenize($text);            $this->k = 0;            if ($word === 'switch') {                $this->expect('case');                $test = $this->number();                $this->expect('goto');                $entries[] = [$test, $this->ident()];            } else {                $this->expect('goto');                $entries[] = [0, $this->ident()];            }            $this->end();        }        $this->line = $line;        if (!$entries) {            $this->fail("$word without a case");        }        $this->emit($word === 'switch' ? "\x2e" : "\x2f");        $this->emitItem($e, 'O');        $this->emit(chr(count($entries) - 1));        if (strlen($this->out) & 1) {            $this->emit(chr($pad));        }        if ($word === 'table') {            $this->emit(pack('v', $base & 0xffff));        }        foreach ($entries as [$test, $label]) {            if ($word === 'switch') {                $this->emit(pack('v', $test & 0xffff));            }            $at = strlen($this->out);            $this->fixups[] = [$at, 2, $at + 2, $label, $this->line];            $this->emit("\0\0");        }    }    // --- expressions ------------------------------------------------------------------------------------------    /** A whole operand: one item, or an oeval of the chain. */    private function expression(bool $untilGoto = false): array    {        $items = $this->chain(false, $untilGoto);        if (!$items) {            $this->fail('expression expected');        }        if (count($items) === 1) {            return $items[0];        }        $items[] = ['c' => 0x3a, 'a' => null, 'sub' => []];        return ['c' => 0x38, 'a' => null, 'sub' => $items];    }    /** Items evaluated left to right, up to ")" (in parentheses), or "," / the end / "goto" outside. */    private function chain(bool $inParens, bool $untilGoto = false): array    {        $items = [];        while ($this->k < count($this->t)) {            [$type, $v] = $this->t[$this->k];            if ($type === 'op' && ($v === ')' || $v === ']' || (!$inParens && $v === ','))) {                break;            }            if ($untilGoto && (($type === 'id' && preg_match('/^goto(\.|$)/', $v)) || ($type === 'op' && $v === '{'))) {                break;            }            if ($type === 'op' && $v === ';') {                $this->k++;                continue;            }            if ($type === 'op' && $v === ',') {                $this->k++;                $items[] = ['c' => 0x40, 'a' => null, 'sub' => []];                continue;            }            $sym = array_search($v, Names::BINOPS, true);            $isBinop = ($type === 'op' || $v === 'eqv') && $sym !== false;            if ($isBinop && $v === '-' && !$items && ($this->t[$this->k + 1][0] ?? '') === 'num') {                $isBinop = false;      // a negative number            }            if ($isBinop) {                $this->k++;                if ($this->peekIs('[')) {                    // A op [B]: push A, compute B, then op with the value popped (opile)                    $this->k++;                    $inner = $this->chain(true);                    $this->expect(']');                    $items[] = ['c' => 0x40, 'a' => null, 'sub' => []];                    array_push($items, ...$inner);                    $items[] = ['c' => self::$codes['O'][$sym], 'a' => null, 'sub' => [['c' => 0x36, 'a' => null, 'sub' => []]]];                    continue;                }                $rhs = $this->element(true);                if (count($rhs) !== 1) {                    $this->fail('the right operand of ' . $v . ' must be one value: put it in parentheses');                }                $items[] = ['c' => self::$codes['O'][$sym], 'a' => null, 'sub' => $rhs];                continue;            }            array_push($items, ...$this->element(false));        }        return $items;    }    /** One element: a value, a call (its arguments' items then the call), a parenthesized chain. */    private function element(bool $single): array    {        [$type, $v] = $this->t[$this->k] ?? ['end', ''];        if ($type === 'op' && $v === '-' && ($this->t[$this->k + 1][0] ?? '') === 'num') {            $this->k++;            $this->t[$this->k][1] = '-' . $this->t[$this->k][1];            [$type, $v] = $this->t[$this->k];        }        if ($type === 'num') {            $this->k++;            return [$this->immediate($v)];        }        if ($type === 'str') {            $this->k++;            return [['c' => 0x04, 'a' => $v, 'sub' => []]];        }        if ($type === 'op' && $v === '(') {            $this->k++;            $sub = $this->chain(true);            $this->expect(')');            $sub[] = ['c' => 0x3a, 'a' => null, 'sub' => []];            return [['c' => 0x38, 'a' => null, 'sub' => $sub]];        }        if ($type !== 'id') {            $this->fail("unexpected $v");        }        $this->k++;        // a variable        $var = $this->variableItem($v, 'O');        if ($var !== null) {            if (Grammar::OPERS[$var['c']][2] !== 't') {                return [$var];            }            $args = $this->args();            if ($single && $args) {                $this->fail('a table read with arguments must be in parentheses here');            }            return [...$args, $var];        }        if ($v === 'push' && !$this->peekIs('(')) {            return [['c' => 0x40, 'a' => null, 'sub' => []]];        }        $name = array_search($v, Names::FUNCS, true);        $fcode = null;        foreach (Names::FUNCS as $oname => $fname) {            if ($fname === $v && isset(self::$codes['O'][$oname]) && in_array(Grammar::OPERS[self::$codes['O'][$oname]][2], ['f', 'x'], true)) {                $fcode = self::$codes['O'][$oname];                break;            }        }        if ($name === false || $fcode === null) {            $this->fail("unknown word $v");        }        $args = $this->args();        if ($single && $args) {            $this->fail("$v(...) with arguments must be in parentheses here");        }        return [...$args, ['c' => $fcode, 'a' => null, 'sub' => []]];    }    /** "(chain)" after a call: its items (empty for "()"). */    private function args(): array    {        $this->expect('(');        $items = $this->chain(true);        $this->expect(')');        return $items;    }    private function immediate(string $text): array    {        $size = null;        if (str_contains($text, ':')) {            [$text, $size] = explode(':', $text);        }        $v = self::parseNumber($text);        $size ??= $v >= -128 && $v <= 127 ? '8' : ($v >= -32768 && $v <= 32767 ? '16' : '32');        return ['c' => ['8' => 0x00, '16' => 0x02, '32' => 0x3c][$size], 'a' => $v, 'sub' => []];    }    /**     * A variable written vb[0x12], vb:loc[0x12], hb[0x30, 0x12]... as an item of $table, or null when $word is     * not a variable prefix.     */    private function variableItem(string $word, string $table): ?array    {        if (!preg_match('/^(v|t|m|mt|h|ht)(b|w|s|o)(:loc)?$/', $word, $m)) {            return null;        }        $this->expect('[');        $a = $this->number();        $b = null;        if ($this->peekIs(',')) {            $this->k++;            $b = $this->number();        }        $this->expect(']');        $type = $m[2];        $isTable = $m[1] === 't' || $m[1] === 'mt' || $m[1] === 'ht' || $type === 'o';        $suffix = $isTable ? ['b' => 'tc', 'w' => 'ti', 's' => 'tp', 'o' => 'to'][$type] : ['b' => 'b', 'w' => 'w', 's' => 'p', 'o' => 'to'][$type];        $letter = ['O' => 'o', 'S' => 's', 'A' => 'a'][$table];        if ($m[1] === 'h' || $m[1] === 'ht') {            if ($b === null) {                $this->fail($word . "[<entity variable>, <offset>]");            }            $mode = 'him';            $a = [$a, $b];        } elseif ($m[1] === 'm' || $m[1] === 'mt') {            $mode = 'main';        } else {            $mode = ($m[3] ?? '') === '' && $a >= 0 && $a <= 255 ? 'dir' : 'loc';        }        $name = $letter . $mode . $suffix;        if (!isset(self::$codes[$table][$name])) {            $this->fail("$word cannot be used here");        }        return ['c' => self::$codes[$table][$name], 'a' => $a, 'sub' => []];    }    /** A store ('S') or add ('A') target; with "(chain)" after it: seval / aeval. */    private function target(string $table): array    {        [$type, $v] = $this->t[$this->k] ?? ['end', ''];        if ($type !== 'id') {            $this->fail('a variable expected');        }        $this->k++;        $item = $this->variableItem($v, $table);        if ($item === null) {            foreach (Names::FUNCS as $oname => $fname) {                if ($fname === $v && isset(self::$codes[$table][$oname])) {                    $item = ['c' => self::$codes[$table][$oname], 'a' => null, 'sub' => []];                    break;                }            }        }        if ($item === null) {            $this->fail("$v is not a variable");        }        if ($this->peekIs('(')) {            $chain = $this->args();            $chain[] = ['c' => 0x3a, 'a' => null, 'sub' => []];            $chain[] = $item;            return ['c' => 0x38, 'a' => null, 'sub' => $chain];        }        return $item;    }    private function emitItem(array $it, string $table): void    {        $tab = ['O' => Grammar::OPERS, 'S' => Grammar::STORES, 'A' => Grammar::ADDS][$table];        [, $spec, $kind] = $tab[$it['c']];        $b = chr($it['c']);        $a = $it['a'];        $b .= match ($spec) {            '' => '',            'b' => ($a < 0 || $a > 255) ? $this->fail('offset out of 0..255') : chr($a),            'w', 'i16' => pack('v', $a & 0xffff),            'h' => pack('vv', $a[0] & 0xffff, $a[1] & 0xffff),            'i8' => chr($a & 0xff),            'i32' => pack('V', $a),            'z' => $a . "\0",        };        $this->emit($b);        if ($kind === 'b') {            $this->emitItem($it['sub'][0], 'O');        } elseif ($kind === 'e') {            foreach ($it['sub'] as $s) {                $this->emitItem($s, 'O');            }        } elseif ($kind === 's') {            $n = count($it['sub']);            foreach ($it['sub'] as $i => $s) {                $this->emitItem($s, $i === $n - 1 ? $table : 'O');            }        }    }    private function emit(string $b): void    {        $this->out .= $b;    }    // --- tokens -----------------------------------------------------------------------------------------------    private function tokenize(string $text): void    {        $this->t = [];        $len = strlen($text);        $i = 0;        while ($i < $len) {            $c = $text[$i];            if ($c === ' ' || $c === "\t") {                $i++;                continue;            }            if ($c === '/' && ($text[$i + 1] ?? '') === '/') {                break;            }            if ($c === '"' || (($c === 'z' || $c === 'h') && preg_match('/\G(z|hex)"/', $text, $m, 0, $i))) {                $kind = $c === '"' ? 'str' : ($c === 'z' ? 'zstr' : 'hex');                $i += $c === '"' ? 1 : ($c === 'z' ? 2 : 4);                $s = '';                while ($i < $len && $text[$i] !== '"') {                    if ($text[$i] === '\\') {                        $n = $text[$i + 1] ?? '';                        if ($n === 'x') {                            $s .= chr(hexdec(substr($text, $i + 2, 2)));                            $i += 4;                            continue;                        }                        $s .= $n === 'n' ? "\n" : $n;                        $i += 2;                        continue;                    }                    $o = ord($text[$i]);                    if ($o >= 0x80 && $kind !== 'hex') {                        // a letter of code page 437 written in UTF-8                        $n = $o >= 0xf0 ? 4 : ($o >= 0xe0 ? 3 : 2);                        $ch = substr($text, $i, $n);                        $byte = array_search($ch, Names::cp437(), true);                        if ($byte === false) {                            $this->fail("the character $ch has no code in the game's texts (code page 437)");                        }                        $s .= chr($byte);                        $i += $n;                        continue;                    }                    $s .= $text[$i++];                }                if ($i >= $len) {                    $this->fail('unterminated string');                }                $i++;                if ($kind === 'hex') {                    if (strlen($s) % 2 || !ctype_xdigit($s) && $s !== '') {                        $this->fail('bad hex"..."');                    }                    $s = (string) hex2bin($s);                }                $this->t[] = [$kind, $s];                continue;            }            if (preg_match('/\G(0x[0-9a-fA-F]+|\d+)(:(8|16|32))?/', $text, $m, 0, $i)) {                $this->t[] = ['num', $m[0]];                $i += strlen($m[0]);                continue;            }            if (preg_match('/\G[A-Za-z_][A-Za-z0-9_]*(:loc|\.(8|16|24)(\/\d+)?)?/', $text, $m, 0, $i)) {                $this->t[] = ['id', $m[0]];                $i += strlen($m[0]);                continue;            }            if (preg_match('/\G(\$==|\$!=|\$<=|\$>=|\$\+|\$<|\$>|==|!=|<=|>=|\+=|-=|[-+*\/%&|^<>=()\[\],;:&{}])/', $text, $m, 0, $i)) {                $this->t[] = ['op', $m[0]];                $i += strlen($m[0]);                continue;            }            $this->fail("unexpected character $c");        }    }    private function findTop(array $ops): ?int    {        $depth = 0;        foreach ($this->t as $i => [$type, $v]) {            if ($type !== 'op') {                continue;            }            if ($v === '(' || $v === '[') {                $depth++;            } elseif ($v === ')' || $v === ']') {                $depth--;            } elseif ($depth === 0 && in_array($v, $ops, true)) {                return $i;            }        }        return null;    }    private function peekIs(string $v): bool    {        $t = $this->t[$this->k] ?? null;        return $t !== null && $t[1] === $v && $t[0] !== 'str';    }    private function expect(string $v): void    {        if (!$this->peekIs($v)) {            $this->fail("$v expected" . (isset($this->t[$this->k]) ? ', not ' . $this->t[$this->k][1] : ''));        }        $this->k++;    }    private function comma(): void    {        $this->expect(',');    }    private function end(): void    {        if ($this->k < count($this->t)) {            $this->fail('unexpected ' . $this->t[$this->k][1]);        }    }    private function ident(): string    {        [$type, $v] = $this->t[$this->k] ?? ['end', ''];        if ($type !== 'id') {            $this->fail('a name expected');        }        $this->k++;        return $v;    }    private function string(): string    {        [$type, $v] = $this->t[$this->k] ?? ['end', ''];        if ($type !== 'str') {            $this->fail('a string expected');        }        $this->k++;        return $v;    }    private function hexBlob(): string    {        [$type, $v] = $this->t[$this->k] ?? ['end', ''];        if ($type !== 'hex') {            $this->fail('hex"..." expected');        }        $this->k++;        return $v;    }    private function number(): int    {        $neg = false;        if ($this->peekIs('-')) {            $neg = true;            $this->k++;        }        [$type, $v] = $this->t[$this->k] ?? ['end', ''];        if ($type !== 'num') {            $this->fail('a number expected');        }        $this->k++;        $n = self::parseNumber(explode(':', $v)[0]);        return $neg ? -$n : $n;    }    private static function parseNumber(string $t): int    {        $neg = str_starts_with($t, '-');        $t = ltrim($t, '-');        $n = str_starts_with($t, '0x') ? (int) hexdec(substr($t, 2)) : (int) $t;        return $neg ? -$n : $n;    }    private function fail(string $msg): never    {        throw new CompileError("line {$this->line}: $msg", $this->line);    }}