UK
games/rob-revisited / src / Revisited / I18n / Extractor.php · commit f9a1307
<?phpnamespace App\Revisited\I18n;/** * Finds the French player-visible strings of a PHP file with PHP's tokenizer (tools/reborn/i18n_extract.php, * tests/RevisitedI18nTest.php). A string expression (a literal, a concatenation chain, an interpolated string, the * format of sprintf) becomes one key; its non-literal parts become {0}, {1}... (Translator matches them back). */final class Extractor{    /** Tokens that end an operand of a concatenation (at bracket depth 0). */    private const STOP = [',', ';', '=', '?', ':', '<', '>', '!', '&', '|', '@', '{', '}',        T_DOUBLE_ARROW, T_RETURN, T_ECHO, T_PRINT, T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL,        T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, T_BOOLEAN_AND, T_BOOLEAN_OR, T_LOGICAL_AND, T_LOGICAL_OR,        T_COALESCE, T_CONCAT_EQUAL, T_PLUS_EQUAL, T_MINUS_EQUAL, T_MUL_EQUAL, T_DIV_EQUAL, T_COALESCE_EQUAL,        T_SPACESHIP, T_FN, T_FUNCTION, T_MATCH, T_CASE, T_NEW, T_THROW, T_YIELD, T_INSTANCEOF, T_IF, T_ELSE,        T_FOREACH, T_AS, T_CONST, T_PUBLIC, T_PRIVATE, T_PROTECTED, T_STATIC, T_OPEN_TAG];    private const FRENCH_WORDS = ['le', 'la', 'les', 'un', 'une', 'des', 'du', 'de', 'et', 'est', 'tu', 'te', 'ton',        'ta', 'tes', 'au', 'aux', 'pour', 'avec', 'sans', 'sur', 'dans', 'pas', 'plus', 'il', 'elle', 'ils', 'on',        'nous', 'vous', 'ne', 'que', 'qui', 'ce', 'cette', 'ces', 'mon', 'ma', 'mes', 'son', 'sa', 'ses', 'par', 'mais',        'ou', 'oui', 'non', 'trop', 'peu', 'bien', 'tout', 'rien', 'je', 'j', 'l', 'd', 'qu', 'c', 's', 'n', 'm', 't',        'jour', 'jours', 'nuit', 'eau', 'feu', 'faim', 'soif', 'froid', 'chaud', 'sang', 'mort', 'vie', 'santé', 'aide',        'lent', 'moyen', 'rapide', 'fermer', 'retour', 'choisir', 'manger', 'boire', 'dormir', 'jeter', 'prendre',        'poser', 'tenir', 'porter', 'parler', 'quitter', 'reprendre', 'sauver', 'charger', 'nouvelle', 'partie',        'options', 'vide', 'aucun', 'aucune', 'tête', 'torse', 'bras', 'jambe', 'gauche', 'droite', 'droit'];    private const ENGLISH_WORDS = ['the', 'of', 'to', 'and', 'is', 'not', 'missing', 'unknown', 'failed', 'error',        'for', 'with', 'from', 'cannot', 'invalid', 'no', 'texture', 'shader', 'define', 'if', 'mix', 'fade', 'music',        'out', 'in', 'on', 'at', 'swiftshader', 'llvmpipe', 'render', 'generic'];    /** Display keys: a single capitalised word under one of these keys is a visible name. */    private const DISPLAY_KEYS = ['name', 'label', 'title', 'desc', 'text', 'say', 'line', 'hint', 'msg', 'message',        'cause', 'tip', 'help', 'caption', 'short', 'verb', 'action', 'place', 'zone'];    /** A printf conversion without the space flag ('{1} % de la zone' is not one): %s %d %.1f %02d %+d %1$s */    private const PRINTF = '/%(?:\d+\$)?[-+0#]*\d*(?:\.\d+)?[sdfu]/';    /** 'Jour %d, %02d:%02d' -> 'Jour {0}, {1}:{2}' (%% -> %): the format of sprintf as a template key. */    public static function printfToTokens(string $key): string    {        $i = 0;        return (string) preg_replace_callback('/%%|%(?:(\d+)\$)?[-+0#]*\d*(?:\.\d+)?([sdfFuxXceEgG])/', static function (array $m) use (&$i): string {            if ($m[0] === '%%') {                return '%';            }            return '{' . (($m[1] ?? '') !== '' ? (int) $m[1] - 1 : $i++) . '}';        }, $key);    }    /** @return list<string> */    public static function sourceFiles(string $root): array    {        $files = [$root . '/src/Scene/RevisitedScene.php'];        $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root . '/src/Revisited', \FilesystemIterator::SKIP_DOTS));        foreach ($it as $f) {            $p = (string) $f;            if (str_ends_with($p, '.php') && !str_contains($p, '/I18n/')) {                $files[] = $p;            }        }        sort($files);        return $files;    }    /** @return list<array{0: string, 1: int}> [key, line] in order of appearance (a key may repeat) */    public static function extract(string $code): array    {        $raw = token_get_all($code);        $t = [];        foreach ($raw as $tok) {            if (is_array($tok) && in_array($tok[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {                continue;            }            $t[] = $tok;        }        $n = count($t);        $used = [];        $out = [];        for ($i = 0; $i < $n; $i++) {            if (isset($used[$i]) || !self::isStringStart($t, $i)) {                continue;            }            // sprintf / printf / vsprintf format: the first argument            $fmt = $i >= 2 && $t[$i - 1] === '(' && is_array($t[$i - 2]) && in_array(strtolower($t[$i - 2][1]), ['sprintf', 'printf', 'vsprintf'], true)                && ($t[self::stringEnd($t, $i) + 1] ?? null) === ',';            [$start, $end] = $fmt ? [$i, self::stringEnd($t, $i)] : self::chain($t, $i);            for ($k = $start, $d = 0; $k <= $end; $k++) {                if ($t[$k] === '(' || $t[$k] === '[') {                    $d++;                } elseif ($t[$k] === ')' || $t[$k] === ']') {                    $d--;                } elseif ($d === 0) {                    $used[$k] = true;           // literals inside (...) of the chain are keys of their own too                }            }            // array key / match arm / comparison: an id, not a text            $after = $t[$end + 1] ?? null;            $before = $t[$start - 1] ?? null;            if ((is_array($after) && in_array($after[0], [T_DOUBLE_ARROW, T_IS_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_NOT_EQUAL], true))                || (is_array($before) && in_array($before[0], [T_IS_EQUAL, T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_NOT_EQUAL, T_CASE], true))) {                continue;            }            $key = self::template($t, $start, $end, $fmt);            if ($key === null || !self::visible($key, self::displayKey($t, $start))) {                continue;            }            $out[] = [$key, self::line($t, $i)];        }        return $out;    }    /** Is this key a French text a player reads? ($display: it is the value of a 'name' / 'label' ... entry) */    public static function visible(string $key, bool $display = false): bool    {        $letters = preg_replace('/\{\w+\}/u', '', $key) ?? '';        if (!preg_match('/\p{L}{2,}/u', $letters)) {            return false;        }        // code, shaders, paths, ids, format-only        if (preg_match('/^[a-z]+:\S/', $key) || preg_match('/\bif \(|;\s*\}/', $key)) {            return false;                       // 'npc:Maëva' (an id), shader code        }        if (preg_match('/(gl_|vec[234]|uniform |varying |precision |attribute |#version|\$|::|->|\\\\[A-Z]|<\?)/', $key)) {            return false;        }        if (preg_match('/^#[0-9a-fA-F]{3,8}$/', $key)) {            return false;                       // a colour        }        if (preg_match('/^[\w.\-\/:]+\.(png|wav|ogg|json|php|yaml|glsl|mp3|txt|md|tmj|als|io)$/i', $key)) {            return false;        }        if (preg_match('/^[a-z0-9_.\-\/:]+$/', $letters) && !preg_match('/[àâäçéèêëîïôöûùüœ]/u', $letters)) {            return false;                       // snake_case id, key, path (lower case, no space)        }        if (preg_match('/^%[\w.]+$|^[A-Z_0-9]+$/', $letters) && mb_strlen($letters) < 3) {            return false;        }        if (preg_match('/[àâäçéèêëîïôöûùüÿœæÀÂÇÉÈÊËÎÏÔÛÙÜŒ«»’]/u', $letters)) {            return true;        }        $words = preg_split('/[^\p{L}]+/u', mb_strtolower($letters), -1, PREG_SPLIT_NO_EMPTY) ?: [];        foreach ($words as $w) {            if (in_array($w, self::FRENCH_WORDS, true)) {                return true;            }        }        if ($display && preg_match('/^\p{Lu}/u', trim($letters))) {            return true;                        // 'Silex', 'Os', 'Peau'        }        foreach ($words as $w) {            if (in_array($w, self::ENGLISH_WORDS, true)) {                return false;                   // a developer message            }        }        // several words starting with a capital ('Cavernes profondes', 'Merci, Sela.', 'EN MAIN')        if (preg_match('/[_{};=<>\[\]]|\p{Ll}\p{Lu}/u', $letters)) {            return false;                       // code, camelCase        }        // several words ('Cavernes profondes', 'Merci, Sela.', ' : blessure grave !'), or one capitalised word ('Cendres', 'Vendre…')        return count($words) >= 2 || preg_match('/^\P{L}*\p{Lu}\p{Ll}{2,}\P{L}*$/u', $letters) === 1 || ($display && count($words) === 1);    }    /** @param list<mixed> $t */    private static function isStringStart(array $t, int $i): bool    {        return (is_array($t[$i]) && $t[$i][0] === T_CONSTANT_ENCAPSED_STRING) || $t[$i] === '"' || (is_array($t[$i]) && $t[$i][0] === T_START_HEREDOC);    }    /** @param list<mixed> $t index of the last token of the string starting at $i */    private static function stringEnd(array $t, int $i): int    {        if ($t[$i] === '"') {            for ($j = $i + 1; $j < count($t); $j++) {                if ($t[$j] === '"') {                    return $j;                }            }        }        if (is_array($t[$i]) && $t[$i][0] === T_START_HEREDOC) {            for ($j = $i + 1; $j < count($t); $j++) {                if (is_array($t[$j]) && $t[$j][0] === T_END_HEREDOC) {                    return $j;                }            }        }        return $i;    }    /** @param list<mixed> $t @return array{0: int, 1: int} the concatenation chain around the string at $i */    private static function chain(array $t, int $i): array    {        $start = $i;        $end = self::stringEnd($t, $i);        while (($t[$start - 1] ?? null) === '.') {            $s = self::operandBack($t, $start - 2);            if ($s === null) {                break;            }            $start = $s;        }        while (($t[$end + 1] ?? null) === '.') {            $e = self::operandForward($t, $end + 2);            if ($e === null) {                break;            }            $end = $e;        }        return [$start, $end];    }    /** Does this token end an operand? */    private static function isStop(mixed $tok): bool    {        return in_array(is_array($tok) ? $tok[0] : $tok, self::STOP, true);    }    /** @param list<mixed> $t @return int|null last index of the operand starting at $j */    private static function operandForward(array $t, int $j): ?int    {        $n = count($t);        $depth = 0;        $last = null;        for (; $j < $n; $j++) {            $tok = $t[$j];            if ($depth === 0 && self::isStringStart($t, $j)) {                $j = self::stringEnd($t, $j);                $last = $j;                continue;            }            if (in_array($tok, ['(', '['], true) || (is_array($tok) && in_array($tok[0], [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true))) {                $depth++;            } elseif (in_array($tok, [')', ']'], true) || ($tok === '}' && $depth > 0)) {                if ($depth === 0) {                    return $last;                }                $depth--;            } elseif ($depth === 0 && ($tok === '.' || self::isStop($tok))) {                return $last;            }            $last = $j;        }        return $last;    }    /** @param list<mixed> $t @return int|null first index of the operand ending at $j */    private static function operandBack(array $t, int $j): ?int    {        $depth = 0;        $first = null;        for (; $j >= 0; $j--) {            $tok = $t[$j];            if ($depth === 0 && $tok === '"') {         // an interpolated string: jump to its opening quote                for ($k = $j - 1; $k >= 0 && $t[$k] !== '"'; $k--) {                }                $j = max(0, $k);                $first = $j;                continue;            }            if (in_array($tok, [')', ']'], true)) {                $depth++;            } elseif (in_array($tok, ['(', '['], true)) {                if ($depth === 0) {                    return $first;                }                $depth--;                if ($depth === 0) {                    $first = $j;                    // a call / cast before the parenthesis belongs to the operand                    continue;                }            } elseif ($depth === 0 && ($tok === '.' || self::isStop($tok))) {                return $first;            }            $first = $j;        }        return $first;    }    /** @param list<mixed> $t builds the key; null when the chain has no literal text */    private static function template(array $t, int $start, int $end, bool $fmt): ?string    {        $key = '';        $slot = 0;        $hasText = false;        for ($j = $start; $j <= $end;) {            if (is_array($t[$j]) && $t[$j][0] === T_CONSTANT_ENCAPSED_STRING) {                $key .= self::unquote($t[$j][1]);                $hasText = true;                $j++;            } elseif ($t[$j] === '"' || (is_array($t[$j]) && $t[$j][0] === T_START_HEREDOC)) {                $close = self::stringEnd($t, $j);                $heredoc = $t[$j] !== '"';                for ($k = $j + 1; $k < $close; $k++) {                    $tok = $t[$k];                    if (is_array($tok) && $tok[0] === T_ENCAPSED_AND_WHITESPACE) {                        $key .= $heredoc ? $tok[1] : stripcslashes($tok[1]);                        $hasText = true;                    } else {                        // a variable / {$expr}: skip to its end, one slot                        if ($tok === '{' || (is_array($tok) && in_array($tok[0], [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true))) {                            $d = 1;                            while ($d > 0 && ++$k < $close) {                                $x = $t[$k];                                if ($x === '{' || (is_array($x) && in_array($x[0], [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true))) {                                    $d++;                                } elseif ($x === '}') {                                    $d--;                                }                            }                        } else {                            // $var, $var[...], $var->prop                            while ($k + 1 < $close && !(is_array($t[$k + 1]) && $t[$k + 1][0] === T_ENCAPSED_AND_WHITESPACE)                                && ($t[$k + 1] === '[' || $t[$k + 1] === ']' || (is_array($t[$k + 1]) && in_array($t[$k + 1][0], [T_OBJECT_OPERATOR, T_STRING, T_NUM_STRING, T_VARIABLE], true) && $t[$k + 1][0] !== T_VARIABLE))) {                                $k++;                            }                        }                        $key .= '{' . $slot++ . '}';                    }                }                $j = $close + 1;            } elseif ($t[$j] === '.') {                $j++;            } else {                // a non-literal operand: up to the next '.' at depth 0                $e = self::operandForward($t, $j) ?? $j;                $key .= '{' . $slot++ . '}';                $j = $e + 1;            }        }        if (!$hasText) {            return null;        }        return $fmt || preg_match(self::PRINTF, $key) ? self::printfToTokens($key) : $key;    }    private static function unquote(string $lit): string    {        if ($lit[0] === "'") {            return str_replace(["\\\\", "\\'"], ["\\", "'"], substr($lit, 1, -1));        }        return stripcslashes(substr($lit, 1, -1));    }    /** @param list<mixed> $t is the string the value of a display key ('name' => ...)? */    private static function displayKey(array $t, int $start): bool    {        $a = $t[$start - 1] ?? null;        $b = $t[$start - 2] ?? null;        if (is_array($a) && $a[0] === T_DOUBLE_ARROW && is_array($b) && $b[0] === T_CONSTANT_ENCAPSED_STRING) {            return in_array(trim($b[1], '\'"'), self::DISPLAY_KEYS, true);        }        // a list of texts: [..., 'Silex', ...] in a constant or a call like ->say('...')        return false;    }    /** @param list<mixed> $t */    private static function line(array $t, int $i): int    {        for ($j = $i; $j >= 0; $j--) {            if (is_array($t[$j])) {                return $t[$j][2];            }        }        return 0;    }}