KO
games/alis / src / Editor / Highlighter.php · commit 9c722cf
<?phpnamespace App\Editor;use App\Alis\Lang\Grammar;use App\Alis\Lang\Human;use App\Alis\Lang\Names;/** * Colours of the ALIS source language (docs/language.md) for the editor: one line → spans [text, kind]. * Kinds: comment, string, label (a definition "L0049:"), jump (a label used), keyword (statement), control (if, else, * while, goto...), directive (header: script, id, class...), variable (vb[...], mw[...]...), function, number, text. */final class Highlighter{    private const CONTROL = ['if', 'ifnot', 'else', 'while', 'goto', 'call', 'start', 'loop', 'switch', 'case', 'end', 'table',        'base', 'ifz', 'ifnz', 'ifeq', 'ifne', 'data', 'hex', 'z', 'dim', 'defvect'];    private const DIRECTIVES = ['script', 'id', 'class', 'memory', 'pack', 'check', 'specs', 'resources', 'main', 'before', 'after',        'module', 'numero', 'classe', 'memoire', 'compression', 'controle', 'ressources', 'depart', 'avant', 'apres',        'ACTOR', 'ID', 'CLASS', 'MEMORY', 'PACK', 'CHECK', 'SPECS', 'RESOURCES', 'MAIN', 'BEFORE', 'AFTER'];    /** ALIS BASIC (App\Alis\Lang\Basic): its words of blocks, jumps and operators */    private const BASIC_CONTROL = ['IF', 'THEN', 'ELSE', 'ENDIF', 'WHILE', 'WEND', 'GOTO', 'GOSUB', 'RETURN', 'START', 'LOOP',        'SELECT', 'CASE', 'ENDSELECT', 'TABLE', 'ENDTABLE', 'DATA', 'UNLESS', 'IFZ', 'IFNZ', 'IFEQ', 'IFNE', 'ADD', 'SUB', 'AND',        'OR', 'XOR', 'MOD', 'EQV', 'V'];    /** @var array<string, string> word => kind */    private array $words = [];    /** @var array<string, list<array{0: string, 1: string}>> */    private array $cache = [];    public function __construct()    {        foreach ([Grammar::OPCODES, Grammar::ESC1] as $table) {            foreach ($table as [$name]) {                $this->words[Names::statement($name)] = 'keyword';            }        }        foreach (array_merge(array_values(Names::FUNCS), array_values(Names::BINOPS)) as $f) {            if (preg_match('/^[a-z]+$/', $f)) {                $this->words[$f] = 'function';            }        }        foreach (self::CONTROL as $w) {            $this->words[$w] = 'control';        }        // the "ALIS 90" form (App\Alis\Lang\Human)        foreach (Human::STATEMENTS as $w) {            $this->words[$w] = 'keyword';        }        foreach (Human::FUNCTIONS as $w) {            $this->words[$w] = 'function';        }        foreach ([...array_values(Human::CONTROL), 'alors', 'faire', 'sinon', 'finsi', 'fintantque', 'et', 'ou', 'oux', 'mod', 'equ'] as $w) {            $this->words[$w] = 'control';            $this->human[$w] = true;        }        foreach (['variables', 'fin_variables', 'local', 'global', 'octet', 'mot', 'texte', 'tableau', 'octets', 'mots', 'textes',            'champ', 'zone', 'adresses'] as $w) {            $this->words[$w] = 'directive';        }        // ALIS BASIC: the machine's words in capitals, its blocks, its declarations        foreach (array_keys(Human::STATEMENTS) as $w) {            $this->words[strtoupper($w)] = 'keyword';        }        foreach (array_keys(Human::FUNCTIONS) as $w) {            $this->words[strtoupper($w)] = 'function';        }        foreach (self::BASIC_CONTROL as $w) {            $this->words[$w] = 'control';            $this->human[$w] = true;        }        foreach (['LOCAL', 'GLOBAL', 'FIELD', 'DIM', 'ZONE', 'AT'] as $w) {            $this->words[$w] = 'directive';        }    }    /** @var array<string, true> */    private array $human = [];    /** @var array<string, true> the variables a "ALIS 90" file declares */    private array $names = [];    /** The variables declared by the text (the "variables" block of the ALIS 90 form). @param list<string> $lines */    public function declare(array $lines): void    {        $names = [];        $in = false;        foreach ($lines as $i => $l) {            $t = trim($l);            if ($t === 'variables') {                $in = true;            } elseif ($t === 'fin_variables' || $i > 400) {                break;            } elseif ($in && preg_match('/(\w+)\s+@/', $t, $m)) {                $names[$m[1]] = true;            } elseif (preg_match('/^(?:LOCAL|GLOBAL|FIELD)(?:\s+(?:DIM|ZONE))?\s+(\w+[|&$%]?)/', $t, $m)) {                $names[$m[1]] = true;      // ALIS BASIC            }        }        if ($names !== $this->names) {            $this->names = $names;            $this->cache = [];        }    }    /** @return list<array{0: string, 1: string}> */    public function line(string $line, bool $header = false): array    {        $key = ($header ? 'h' : 'b') . $line;        if (isset($this->cache[$key])) {            return $this->cache[$key];        }        $spans = [];        $n = strlen($line);        $i = 0;        $first = true;        $push = static function (string $text, string $kind) use (&$spans): void {            if ($text === '') {                return;            }            $last = count($spans) - 1;            if ($last >= 0 && $spans[$last][1] === $kind) {                $spans[$last][0] .= $text;            } else {                $spans[] = [$text, $kind];            }        };        while ($i < $n) {            $c = $line[$i];            if (($c === '/' && ($line[$i + 1] ?? '') === '/') || $c === "'") {                $push(substr($line, $i), 'comment');                break;            }            if ($c === '"') {                $j = $i + 1;                while ($j < $n && $line[$j] !== '"') {                    $j += $line[$j] === '\\' ? 2 : 1;                }                $push(substr($line, $i, $j + 1 - $i), 'string');                $i = $j + 1;                continue;            }            if (ctype_alpha($c) || $c === '_') {                preg_match('/\G[A-Za-z_][A-Za-z0-9_.]*[|&$%]?/', $line, $m, 0, $i);                $word = $m[0];                $after = substr($line, $i + strlen($word));                if ($first && str_starts_with($after, ':') && !str_starts_with($after, '::')) {                    $kind = 'label';                } elseif (preg_match('/^(L|proc_|et_|sp_)[0-9a-f]{4,}$/', $word)) {                    $kind = 'jump';                } elseif (isset($this->names[$word])) {                    $kind = 'variable';                } elseif (preg_match('/^(v|t|m|mt|h|ht)[bwso]$/', $word) && str_starts_with(ltrim($after), '[')) {                    $kind = 'variable';                } elseif ($header && $first && in_array($word, self::DIRECTIVES, true)) {                    $kind = 'directive';                } else {                    $base = explode('.', $word)[0];                    $kind = $this->words[$base] ?? 'text';                    if ($kind === 'keyword' && !$first) {                        $kind = isset($this->words[$base]) && (in_array($base, self::CONTROL, true) || isset($this->human[$base])) ? 'control' : 'text';                    }                }                $push($word, $kind);                $i += strlen($word);                $first = false;                if ($kind === 'label') {                    $push(':', 'label');                    $i++;                    $first = true;      // a statement may follow its label                }                continue;            }            if ($c === '&' && ($line[$i + 1] ?? '') === 'H' && ctype_xdigit($line[$i + 2] ?? '')) {                preg_match('/\G&H[0-9a-fA-F]+/', $line, $m, 0, $i);                $push($m[0], 'number');                $i += strlen($m[0]);                $first = false;                continue;            }            if (ctype_digit($c) || ($c === '$' && ctype_xdigit($line[$i + 1] ?? '')) || ($c === '-' && (ctype_digit($line[$i + 1] ?? '') || ($line[$i + 1] ?? '') === '$') && $first === false && preg_match('/[\s,(\[]$/', substr($line, 0, $i)))) {                preg_match('/\G-?(0x[0-9a-fA-F]+|\$[0-9a-fA-F]+|\d+)(:\d+)?/', $line, $m, 0, $i);                $push($m[0], 'number');                $i += strlen($m[0]);                $first = false;                continue;            }            if ($c !== ' ' && $c !== "\t") {                $first = $first && $c === '}';            }            $push($c, 'text');            $i++;        }        if (count($this->cache) > 3000) {            $this->cache = [];        }        return $this->cache[$key] = $spans;    }}