PT
games/alis / src / Alis / Lang / Basic.php · commit 9c722cf
<?phpnamespace App\Alis\Lang;/** * "ALIS BASIC" (docs/language.md, "ALIS BASIC"): the scripts as Silmarils' developers most likely wrote them on their * Atari ST around 1990. The machine's own words are the original ones (the opcode tables of the Silmarils Collection * CD: putnat, topalet, mouson, live, kill...) and many of them are BASIC keywords (locate, tab, dim, random, loop, * plot, draw, box, boxf, ink, mouse): a BASIC of the time, in the manner of GFA BASIC, the language of the Atari ST * in France. So: UPPERCASE keywords, IF / ELSE / ENDIF, WHILE / WEND, GOSUB / RETURN, SELECT / CASE / ENDSELECT, * ADD / SUB, &H hexadecimal, ' comments, typed variables (| byte, & word, $ text, % address) declared with LOCAL / * GLOBAL / FIELD, V: for an address, AND / OR / XOR / MOD, = for both a store and a comparison. * * Like the "90" form (Human) it is a word for word translation of the canonical form: toCanonical(toBasic($s)) === $s, * and a BASIC file compiles to the same bytes. isBasic() tells it apart (a BASIC file has an `ACTOR "..."` line). */final class Basic{    /** canonical prefix => [scope, suffix, name prefix, kind word of the declaration] */    private const KINDS = [        'vb' => ['LOCAL', '|', 'v_', ''], 'vw' => ['LOCAL', '&', 'v_', ''], 'vs' => ['LOCAL', '$', 's_', ''],        'tb' => ['LOCAL', '|', 't_', 'DIM'], 'tw' => ['LOCAL', '&', 't_', 'DIM'], 'ts' => ['LOCAL', '$', 't_', 'DIM'],        'to' => ['LOCAL', '%', 'a_', 'DIM'],        'mb' => ['GLOBAL', '|', 'g_', ''], 'mw' => ['GLOBAL', '&', 'g_', ''], 'ms' => ['GLOBAL', '$', 'gs_', ''],        'mtb' => ['GLOBAL', '|', 'gt_', 'DIM'], 'mtw' => ['GLOBAL', '&', 'gt_', 'DIM'], 'mts' => ['GLOBAL', '$', 'gt_', 'DIM'],        'hb' => ['FIELD', '|', 'c_', ''], 'hw' => ['FIELD', '&', 'c_', ''], 'hs' => ['FIELD', '$', 'c_', ''],        'hts' => ['FIELD', '$', 'ct_', 'DIM'],        '&v' => ['LOCAL', '', 'z_', 'ZONE'], '&m' => ['GLOBAL', '', 'gz_', 'ZONE'],    ];    /** the words of the blocks and jumps (canonical => BASIC) */    private const CONTROL = [        'goto' => 'GOTO', 'call' => 'GOSUB', 'ret' => 'RETURN', 'start' => 'START', 'loop' => 'LOOP', 'switch' => 'SELECT',        'case' => 'CASE', 'table' => 'TABLE', 'data' => 'DATA', 'if' => 'IF', 'while' => 'WHILE', 'ifnot' => 'UNLESS',        'ifz' => 'IFZ', 'ifnz' => 'IFNZ', 'ifeq' => 'IFEQ', 'ifne' => 'IFNE',    ];    private const DIRECTIVES = [        'script' => 'ACTOR', 'id' => 'ID', 'class' => 'CLASS', 'memory' => 'MEMORY', 'pack' => 'PACK', 'check' => 'CHECK',        'resources' => 'RESOURCES', 'main' => 'MAIN', 'before' => 'BEFORE', 'after' => 'AFTER',    ];    /** operators (canonical => BASIC); a store stays =, the comparison == becomes = too (BASIC tells them apart by place) */    private const OPERATORS = [        '==' => '=', '!=' => '<>', '&' => 'AND', '|' => 'OR', '^' => 'XOR', '%' => 'MOD', 'eqv' => 'EQV',        '$==' => '$=', '$!=' => '$<>',    ];    /** words of the canonical form written in capitals (the rest, e.g. an unknown function, stays as it is) */    private const EXTRA_WORDS = ['neg', 'scan', 'abs', 'config', 'mip'];    private const TOKEN_CANON = '/\G(\s+|\/\/.*|"(?:[^"\\\\]|\\\\.)*"|0x[0-9a-fA-F]+|\d+|[A-Za-z_][A-Za-z0-9_]*(?:\.\d+)?'        . '|\$==|\$!=|\$<=|\$>=|\$<>|\$\+|\$<|\$>|\$=|==|!=|<=|>=|<>|\+=|-=|->|.)/s';    private const TOKEN_BASIC = '/\G(\s+|\'.*|"(?:[^"\\\\]|\\\\.)*"|&H[0-9a-fA-F]+|\d+|[A-Za-z_][A-Za-z0-9_]*[|&$%]?(?:\.\d+)?'        . '|\$<=|\$>=|\$<>|\$\+|\$<|\$>|\$=|<=|>=|<>|.)/s';    public static function isBasic(string $source): bool    {        return (bool) preg_match('/^\s*ACTOR\s+"/m', $source);    }    /** @return array<string, string> lowercase canonical word => BASIC word */    private static function words(): array    {        static $w = null;        if ($w === null) {            $w = [];            foreach ([...array_keys(Human::STATEMENTS), ...array_keys(Human::FUNCTIONS), ...self::EXTRA_WORDS] as $k) {                $w[$k] = strtoupper($k);            }        }        return $w;    }    /** @return list<string> */    private static function tokens(string $re, string $line): array    {        preg_match_all($re, $line, $m);        return $m[0];    }    // --- canonical -> BASIC -------------------------------------------------------------------------------------    public static function toBasic(string $canonical): string    {        $script = preg_match('/^\s*script\s+"([^"]+)"/m', $canonical, $m) ? strtolower($m[1]) : '';        $lines = explode("\n", $canonical);        $procs = [];        foreach ($lines as $line) {            if (preg_match_all('/\b(?:call|start|main|before|after)(?:\.\d+)?\s+(L[0-9a-f]{4,})\b/', $line, $mm)) {                foreach ($mm[1] as $l) {                    $procs[$l] = true;                }            }        }        $names = new \ArrayObject();        $out = [];        $blocks = [];        foreach ($lines as $line) {            $out[] = self::lineToBasic($line, $names, $procs, $script, $blocks);        }        if (count($names) > 0) {            $at = 0;            foreach ($out as $i => $l) {                if (preg_match('/^\s*(ACTOR|ID|CLASS|MEMORY|PACK|CHECK|SPECS|RESOURCES|MAIN|BEFORE|AFTER)\b/', $l)) {                    $at = $i + 1;                } elseif ($at > 0 && trim($l) !== '' && !str_starts_with(ltrim($l), "'")) {                    break;                }            }            array_splice($out, $at, 0, array_merge([''], self::declarations($names)));        }        return implode("\n", $out);    }    private static function lineToBasic(string $line, \ArrayObject $names, array $procs, string $script, array &$blocks): string    {        $indent = (string) preg_replace('/\S.*$/s', '', $line);        $body = substr($line, strlen($indent));        if ($body === '}') {            return $indent . (array_pop($blocks) === 'while' ? 'WEND' : 'ENDIF');        }        if ($body === '} else {') {            return $indent . 'ELSE';        }        if ($body === 'end') {            return $indent . (array_pop($blocks) === 'table' ? 'ENDTABLE' : 'ENDSELECT');        }        if (preg_match('/^(if|while) (.*) \{$/s', $body, $m)) {            $blocks[] = $m[1];            $body = $m[1] . ' ' . $m[2];        } elseif (preg_match('/^(switch|table)\b/', $body, $m)) {            $blocks[] = $m[1];        }        // a store that adds / subtracts: ADD x, n / SUB x, n        $add = null;        if (preg_match('/^(.+?) (\+=|-=) (.*)$/s', $body, $m) && !preg_match('/^(if|ifnot|while)\b/', $body)) {            $add = $m[2] === '+=' ? 'ADD ' : 'SUB ';            $body = $m[1] . ', ' . $m[3];        }        $t = self::tokens(self::TOKEN_CANON, $body);        $n = count($t);        $o = '';        for ($i = 0; $i < $n; $i++) {            $tok = $t[$i];            $prefix = null;            if ($tok === '&' && in_array($t[$i + 1] ?? '', ['v', 'm'], true) && ($t[$i + 2] ?? '') === '[') {                $prefix = '&' . $t[$i + 1];                $i++;            } elseif (isset(self::KINDS[$tok]) && ($t[$i + 1] ?? '') === '[') {                $prefix = $tok;            }            if ($prefix !== null) {                $inner = '';                for ($j = $i + 2; $j < $n && $t[$j] !== ']'; $j++) {                    $inner .= $t[$j];                }                $o .= self::nameOf($prefix . '[' . $inner . ']', $prefix, $inner, $names, $script);                $i = $j;                continue;            }            if (str_starts_with($tok, '//')) {                $o .= "'" . substr($tok, 2);                continue;            }            if (str_starts_with($tok, '0x')) {                $o .= '&H' . strtoupper(substr($tok, 2));                continue;            }            if (preg_match('/^[A-Za-z_]/', $tok)) {                if (($tok === 'z' || $tok === 'hex') && (($t[$i + 1] ?? '')[0] ?? '') === '"') {                    $o .= $tok;                    continue;                }                $first = trim($o) === '';                if (preg_match('/^L([0-9a-f]{4,})$/', $tok, $lm)) {                    $o .= (isset($procs[$tok]) ? 'sp_' : 'et_') . $lm[1];                } elseif ($first && isset(self::DIRECTIVES[$tok])) {                    $o .= self::DIRECTIVES[$tok];                } elseif (isset(self::CONTROL[$tok])) {                    $o .= self::CONTROL[$tok];                } elseif (isset(self::OPERATORS[$tok])) {                    $o .= self::OPERATORS[$tok];                } else {                    $o .= self::words()[$tok] ?? $tok;                }                continue;            }            $o .= self::OPERATORS[$tok] ?? $tok;        }        // IF x goto L (a jump, not a block): IF x THEN GOTO L        if (preg_match('/^(IF|UNLESS|IFZ|IFNZ|IFEQ|IFNE) (.*) (GOTO|GOSUB) (\w+)$/s', $o, $m) && !preg_match('/\{$/', $line)) {            $o = "$m[1] $m[2] THEN $m[3] $m[4]";        }        return $indent . ($add ?? '') . $o;    }    private static function nameOf(string $canon, string $prefix, string $inner, \ArrayObject $names, string $script): string    {        if (str_contains($inner, ':')) {            return $canon;                      // a variable in its long form (vb:loc[...]): as it is        }        if ($prefix[0] === 'h') {            [$ent, $field] = array_map('trim', explode(',', $inner, 2)) + [1 => '0x0'];            return self::nameOf("vw[$ent]", 'vw', $ent, $names, $script) . '.' . self::declare($prefix . "[*, $field]", $prefix, $field, $names, $script);        }        $name = self::declare($canon, $prefix, $inner, $names, $script);        return $prefix[0] === '&' ? 'V:' . $name : $name;    }    private static function declare(string $key, string $prefix, string $off, \ArrayObject $names, string $script): string    {        if (!isset($names[$key])) {            [, $suffix, $base] = self::KINDS[$prefix];            $known = Human::KNOWN_LOCAL[$script][$key] ?? Human::KNOWN[$key] ?? null;            $name = ($known ?? $base . str_replace(['-0x', '0x'], ['m', ''], $off)) . $suffix;            $names[$key] = [$name, $prefix, $off];        }        return $names[$key][0];    }    /** @return list<string> */    private static function declarations(\ArrayObject $names): array    {        $rows = [];        foreach ($names as [$name, $prefix, $off]) {            [$scope, , , $kind] = self::KINDS[$prefix];            $hex = preg_replace_callback('/(-?)0x([0-9a-fA-F]+)/', static fn ($m) => $m[1] . '&H' . strtoupper($m[2]), $off);            $rows[] = [trim("$scope $kind"), $name . ($kind === 'DIM' ? '()' : ''), $hex, $prefix];        }        $order = ['LOCAL' => 0, 'LOCAL DIM' => 1, 'LOCAL ZONE' => 2, 'GLOBAL' => 3, 'GLOBAL DIM' => 4, 'GLOBAL ZONE' => 5, 'FIELD' => 6, 'FIELD DIM' => 7];        usort($rows, static fn ($a, $b) => [$order[$a[0]] ?? 9, $a[1]] <=> [$order[$b[0]] ?? 9, $b[1]]);        $w1 = max(array_map(static fn ($r) => strlen($r[0]), $rows));        $w2 = max(array_map(static fn ($r) => strlen($r[1]), $rows));        $out = [];        foreach ($rows as [$kind, $name, $hex]) {            $out[] = str_pad($kind, $w1) . '  ' . str_pad($name, $w2) . '  AT ' . $hex;        }        return $out;    }    // --- BASIC -> canonical -------------------------------------------------------------------------------------    /** @var list<int> after toCanonical(): the BASIC file's line (1-based) of each canonical line */    public static array $lines = [];    public static function toCanonical(string $basic): string    {        $lines = explode("\n", $basic);        $vars = [];        // name => canonical text        $fields = [];      // name => [prefix, offset]        $keep = [];        $keepAt = [];        $first = null;        foreach ($lines as $k => $line) {            if (preg_match('/^(LOCAL|GLOBAL|FIELD)(?:\s+(DIM|ZONE))?\s+(\w+?)([|&$%]?)(\(\))?\s+AT\s+(-?)&H([0-9a-fA-F]+)$/', trim($line), $m)) {                $first ??= count($keep);                [, $scope, $kind, $base, $suffix, , $neg, $hex] = $m;                $name = $base . $suffix;                $prefix = self::prefixOf($scope, $kind, $suffix);                if ($prefix === null) {                    throw new CompileError('line ' . ($k + 1) . ": $name: no such variable kind ($scope $kind with \"$suffix\")", $k + 1);                }                $off = $neg . '0x' . strtolower($hex);                if ($prefix[0] === 'h') {                    $fields[$name] = [$prefix, $off];                } else {                    $vars[$name] = $prefix . '[' . $off . ']';                }                continue;            }            $keep[] = $line;            $keepAt[] = $k + 1;        }        // the blank line given before the declarations        if ($first !== null && $first > 0 && trim($keep[$first - 1]) === '') {            array_splice($keep, $first - 1, 1);            array_splice($keepAt, $first - 1, 1);        }        self::$lines = $keepAt;        $words = array_flip(self::words());        $control = array_flip(self::CONTROL);        $directives = array_flip(self::DIRECTIVES);        $operators = array_flip(self::OPERATORS);        $out = [];        foreach ($keep as $idx => $line) {            try {                $out[] = self::lineToCanonical($line, $vars, $fields, $words, $control, $directives, $operators);            } catch (CompileError $e) {                $at = $keepAt[$idx];                throw new CompileError("line $at: " . $e->getMessage(), $at);            }        }        return implode("\n", $out);    }    /**     * @param array<string, string> $vars     * @param array<string, array{0: string, 1: string}> $fields     * @param array<string, string> $words     * @param array<string, string> $control     * @param array<string, string> $directives     * @param array<string, string> $operators     */    private static function lineToCanonical(string $line, array $vars, array $fields, array $words, array $control, array $directives, array $operators): string    {        $indent = (string) preg_replace('/\S.*$/s', '', $line);        $body = substr($line, strlen($indent));        if ($body === 'ENDIF' || $body === 'WEND') {            return $indent . '}';        }        if ($body === 'ELSE') {            return $indent . '} else {';        }        if ($body === 'ENDSELECT' || $body === 'ENDTABLE') {            return $indent . 'end';        }        $suffix = '';        $add = null;        if (preg_match('/^(IF|UNLESS|IFZ|IFNZ|IFEQ|IFNE) (.*) THEN (GOTO|GOSUB) (\w+)$/s', $body, $m)) {            $body = "$m[1] $m[2] $m[3] $m[4]";        } elseif (preg_match('/^(IF|WHILE) (.*)$/s', $body, $m)) {            $suffix = ' {';        } elseif (preg_match('/^(ADD|SUB) (.*)$/s', $body, $m)) {            $add = $m[1] === 'ADD' ? '+=' : '-=';            $body = $m[2];        }        $t = self::tokens(self::TOKEN_BASIC, $body);        $n = count($t);        // an assignment: the line starts with a variable, its first = (outside brackets) is the store        $store = -1;        if ($add === null && $n > 0 && (isset($vars[$t[0]]) || preg_match('/^[a-z_]\w*[|&$%]$/', $t[0]))) {            $depth = 0;            for ($i = 0; $i < $n; $i++) {                $depth += $t[$i] === '(' || $t[$i] === '[' ? 1 : ($t[$i] === ')' || $t[$i] === ']' ? -1 : 0);                if ($depth === 0 && $t[$i] === '=') {                    $store = $i;                    break;                }            }        }        $o = '';        $depth = 0;        for ($i = 0; $i < $n; $i++) {            $tok = $t[$i];            if ($add !== null && $depth === 0 && $tok === ',') {                $o = rtrim($o) . ' ' . $add;     // ADD x, n -> x += n (the comma that ends the target)                $add = null;                continue;            }            $depth += $tok === '(' || $tok === '[' ? 1 : ($tok === ')' || $tok === ']' ? -1 : 0);            if ($tok[0] === "'") {                $o .= '//' . substr($tok, 1);                continue;            }            if (str_starts_with($tok, '&H')) {                $o .= '0x' . strtolower(substr($tok, 2));                continue;            }            if ($tok === '=') {                $o .= $i === $store ? '=' : '==';                continue;            }            if ($tok === 'V' && ($t[$i + 1] ?? '') === ':' && isset($vars[$t[$i + 2] ?? ''])) {                $o .= $vars[$t[$i + 2]];                $i += 2;                continue;            }            if (preg_match('/^[A-Za-z_]/', $tok)) {                if (($tok === 'z' || $tok === 'hex') && (($t[$i + 1] ?? '')[0] ?? '') === '"') {                    $o .= $tok;                    continue;                }                // another entity's field: ent.field                if (($t[$i + 1] ?? '') === '.' && isset($fields[$t[$i + 2] ?? ''])) {                    $ent = $vars[$tok] ?? null;                    if ($ent === null || !preg_match('/^vw\[(.+)\]$/', $ent, $em)) {                        throw new CompileError("$tok.{$t[$i + 2]}: $tok is not a declared word");                    }                    [$fp, $foff] = $fields[$t[$i + 2]];                    $o .= $fp . '[' . $em[1] . ', ' . $foff . ']';                    $i += 2;                    continue;                }                if (isset($vars[$tok])) {                    $o .= $vars[$tok];                    continue;                }                $firstWord = trim($o) === '';                $o .= match (true) {                    $firstWord && isset($directives[$tok]) => $directives[$tok],                    isset($control[$tok]) => $control[$tok],                    isset($operators[$tok]) => $operators[$tok],                    (bool) preg_match('/^(?:sp|et)_([0-9a-f]{4,})$/', $tok, $lm) => 'L' . $lm[1],                    isset($words[$tok]) => $words[$tok],                    (bool) preg_match('/^[a-z_]\w*[|&$%]$/', $tok) => throw new CompileError("$tok is not declared (LOCAL / GLOBAL ... AT &H...)"),                    default => $tok,                };                continue;            }            $o .= $operators[$tok] ?? $tok;        }        return $indent . $o . $suffix;    }    private static function prefixOf(string $scope, string $kind, string $suffix): ?string    {        foreach (self::KINDS as $prefix => [$sc, $sf, , $k]) {            if ($sc === $scope && $k === $kind && $sf === $suffix) {                return $prefix;            }        }        return null;    }    /** A canonical line number (a compile error) -> the BASIC file's. */    public static function basicLine(int $canonicalLine): int    {        return self::$lines[$canonicalLine - 1] ?? $canonicalLine;    }}