Skip to content

Commit 14dfcab

Browse files
committed
Derive token names instead of shipping a name table
Drop the generated TOKEN_NAMES map (half of tokens.php) and derive diagnostic token names at runtime instead: a keyword token resolves to its keyword string by inverting KEYWORDS, any other token to its WP_MySQL_Tokens constant name by reflection. Every emittable token id is covered — the dropped map's extra entries were terminals the lexer can never emit. On synonym collisions, plain keywords win over paren-gated function variants (USER over SESSION_USER). The map is built lazily on the first get_token_name() call, which is a debug-only path. tokens.php shrinks from 41 KB to 20 KB.
1 parent 2beadb5 commit 14dfcab

6 files changed

Lines changed: 97 additions & 892 deletions

File tree

‎packages/mysql-parser/src/class-wp-mysql-lexer.php‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,13 @@ public static function get_token_id( string $token_name ): ?int {
430430
/**
431431
* Get the name of a token for a given token ID.
432432
*
433+
* Names are derived from the grammar data rather than stored: a keyword
434+
* token resolves to its keyword string via self::KEYWORDS, any other token
435+
* to its WP_MySQL_Tokens constant name via reflection. When several names
436+
* share a token number (keyword synonyms, equal-valued constants), plain
437+
* keywords win over paren-gated function keywords (USER over SESSION_USER),
438+
* then the first name in table order wins.
439+
*
433440
* This method is intended to be used only for testing and debugging purposes,
434441
* when tokens need to be presented by their names in a human-readable form.
435442
* It should not be used in production code, as it's not performance-optimized.
@@ -438,7 +445,26 @@ public static function get_token_id( string $token_name ): ?int {
438445
* @return string The token name for the given token ID; null when not found.
439446
*/
440447
public static function get_token_name( int $token_id ): ?string {
441-
return self::TOKEN_NAMES[ $token_id ] ?? null;
448+
static $names = null;
449+
if ( null === $names ) {
450+
$names = array();
451+
foreach ( self::KEYWORDS as $keyword => $id ) {
452+
if ( ! isset( $names[ $id ] ) && ! isset( self::FUNCTIONS[ $keyword ] ) ) {
453+
$names[ $id ] = $keyword;
454+
}
455+
}
456+
foreach ( self::KEYWORDS as $keyword => $id ) {
457+
if ( ! isset( $names[ $id ] ) ) {
458+
$names[ $id ] = $keyword;
459+
}
460+
}
461+
foreach ( ( new ReflectionClass( WP_MySQL_Tokens::class ) )->getConstants() as $name => $value ) {
462+
if ( is_int( $value ) && ! isset( $names[ $value ] ) ) {
463+
$names[ $value ] = $name;
464+
}
465+
}
466+
}
467+
return $names[ $token_id ] ?? null;
442468
}
443469

444470
private function read_next_token(): ?int {

0 commit comments

Comments
 (0)