Skip to content

Commit 296a9c5

Browse files
committed
Shrink the parse table with structural encodings
Cut the generated parse table from 231 KB to 182 KB, with no behavior change: modal shift targets stored as bare token lists, GOTO exceptions keyed by nonterminal instead of state, rule names indexed by the contiguous lhs ids, and short array syntax in the emitted literals. The smaller file also parses faster on a cold opcache.
1 parent 7efac97 commit 296a9c5

4 files changed

Lines changed: 124 additions & 55 deletions

File tree

‎packages/mysql-parser/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,9 @@ MySQL query ──▶ WP_MySQL_Lexer ──▶ grammar tokens ──▶ WP_MySQL
3232
Docker, version-asserted), and compacts Bison's `--xml` automaton into plain
3333
PHP ACTION/GOTO tables: per-state default reductions with sparse exception
3434
rows, identical rows shared between states, near-identical keyword rows
35-
patch-encoded against a base row, and per-nonterminal GOTO defaults — about
36-
7% of the cells of the dense table. A second generator
35+
patch-encoded against a base row, modal per-terminal shift targets, and
36+
per-nonterminal GOTO defaults — about 7% of the cells of the dense table.
37+
A second generator
3738
derives the token-level data — the keyword table, the paren-gated function
3839
keywords, and the token constants the scanner refers to — from `lex.h` and
3940
the automaton, resolving every terminal by name.

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

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,18 +38,18 @@ class WP_MySQL_Parser {
3838
private $action; // State => row (shared between states).
3939
private $action_default; // State => default reduce code.
4040

41-
// GOTO: per-nonterminal default target + sparse per-state exceptions.
42-
private $goto_exceptions; // State => ( nonterminal id => target state ).
41+
// GOTO: per-nonterminal default target + sparse exceptions.
42+
private $goto_exceptions; // Nonterminal id => ( state => target state ).
4343
private $goto_default; // Nonterminal id => default target state.
4444

4545
// Productions.
4646
private $rule_lhs; // Production id => lhs nonterminal id.
4747
private $rule_len; // Production id => rhs length.
4848
private $rule_name; // Production id => rule name.
4949

50-
private $state_count; // Number of states (also the accept code).
50+
private $state_count; // Number of states (also the accept code).
5151
private $start; // Start state.
52-
private $end_token; // End-of-input token number ($end).
52+
private $end_token; // End-of-input token number ($end).
5353

5454
/** Whether unit productions over a node are inlined instead of wrapped. */
5555
private $inline_unit_productions;
@@ -61,10 +61,18 @@ public function __construct( array $table, bool $inline_unit_productions = false
6161
$this->start = $table['start'];
6262
$this->end_token = $table['dollar'];
6363

64-
// Materialise the patch-encoded rows: a patch holds only the cells that
65-
// differ from its base row, so the union "patch + base" reconstructs the
66-
// full row (bases always precede their patches).
67-
$rows = $table['rows'];
64+
// Materialise the rows: first restore the shift cells stored as bare
65+
// token lists from the per-terminal modal target table, then apply the
66+
// patch encoding — a patch holds only the cells that differ from its
67+
// base row, so the union "patch + base" reconstructs the full row
68+
// (bases always precede their patches).
69+
$rows = $table['rows'];
70+
$shift_target = $table['shift_target'];
71+
foreach ( $table['row_shifts'] as $row_id => $tokens ) {
72+
foreach ( $tokens as $token ) {
73+
$rows[ $row_id ][ $token ] = $shift_target[ $token ];
74+
}
75+
}
6876
foreach ( $table['row_base'] as $row_id => $base_row_id ) {
6977
$rows[ $row_id ] += $rows[ $base_row_id ];
7078
}
@@ -83,10 +91,12 @@ public function __construct( array $table, bool $inline_unit_productions = false
8391
$this->rule_len = $table['rule_len'];
8492

8593
// Resolve each production's rule name once, off the reduce hot path.
94+
// The names list is ordered by the grammar's contiguous nonterminal ids.
8695
$names = $table['names'];
96+
$lhs_base = $table['lhs_base'];
8797
$this->rule_name = array();
88-
foreach ( $table['rule_name'] as $production => $name_index ) {
89-
$this->rule_name[ $production ] = $names[ $name_index ];
98+
foreach ( $table['rule_lhs'] as $production => $lhs ) {
99+
$this->rule_name[ $production ] = $names[ $lhs - $lhs_base ];
90100
}
91101
}
92102

@@ -178,7 +188,7 @@ public function parse( array $tokens ) {
178188
}
179189

180190
// GOTO on $lhs from the state now exposed under the handle.
181-
$state_stack[ $base + 1 ] = $goto_exceptions[ $state_stack[ $base ] ][ $lhs ] ?? $goto_default[ $lhs ];
191+
$state_stack[ $base + 1 ] = $goto_exceptions[ $lhs ][ $state_stack[ $base ] ] ?? $goto_default[ $lhs ];
182192
$top = $base + 1;
183193
}
184194
}

‎packages/mysql-parser/src/grammar/parse-table.php‎

Lines changed: 14 additions & 12 deletions
Large diffs are not rendered by default.

‎packages/mysql-parser/tools/generate-parse-table.php‎

Lines changed: 86 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,27 @@
88
* shift/reduce conflict by precedence and reports zero reduce/reduce
99
* conflicts), so each (state, token) cell holds a single action.
1010
*
11-
* The table is kept small with three structural devices, all in plain PHP:
11+
* The table is kept small with four structural devices, all in plain PHP:
1212
*
1313
* 1. Per-state default reduce ('state_default'): most states reduce by the
1414
* same production for nearly every lookahead; only differing cells are
1515
* stored, as sparse token => action rows.
1616
* 2. Row sharing ('state_row'): states with identical cell sets point at a
1717
* single shared row.
1818
* 3. Patch rows ('row_base'): the keyword-heavy rows are hundreds of cells
19-
* each but nearly identical to one another (a keyword reduces by the same
20-
* keyword-as-identifier production in every such state), so a row may be
21-
* stored as a small patch over an earlier base row; the runtime applies
22-
* patches with an array union at construction time.
19+
* each but nearly identical to one another, so a row may be stored as a
20+
* small patch over an earlier base row; the runtime applies patches with
21+
* an array union at construction time.
22+
* 4. Modal shift targets ('shift_target' + 'row_shifts'): most shifts on a
23+
* given terminal go to the same successor state, so such cells are
24+
* stored as bare token lists and restored from a per-terminal target
25+
* table at construction time.
2326
*
2427
* GOTO targets cluster by nonterminal instead, so they are stored as a
25-
* per-nonterminal default ('goto_default') plus sparse per-state exceptions
26-
* ('goto_exceptions').
28+
* per-nonterminal default ('goto_default') plus sparse exceptions keyed by
29+
* nonterminal ('goto_exceptions'). Rule names need no per-production index:
30+
* the names list is ordered by the (contiguous) nonterminal ids, so a
31+
* rule's name is names[lhs - lhs_base].
2732
*
2833
* Action codes (int): 0 = syntax error; a positive code below the state count
2934
* = shift to that state; the state count = accept; a negative code = reduce
@@ -230,6 +235,47 @@ function ( $t, $c ) {
230235
$stored_cells += count( $emitted[ $row_id ] );
231236
}
232237

238+
/*
239+
* Modal shift targets: for each terminal, find the most common shift target
240+
* among the stored cells. Cells that hit it are emitted as bare token lists
241+
* ('row_shifts') instead of token => target pairs; the runtime restores them
242+
* from the per-terminal table ('shift_target') at construction time.
243+
*/
244+
$shift_freq = array();
245+
foreach ( $emitted as $cells ) {
246+
foreach ( $cells as $token => $code ) {
247+
if ( $code > 0 && $code < $state_count ) {
248+
$shift_freq[ $token ][ $code ] = ( $shift_freq[ $token ][ $code ] ?? 0 ) + 1;
249+
}
250+
}
251+
}
252+
ksort( $shift_freq );
253+
$shift_target = array();
254+
foreach ( $shift_freq as $token => $freq ) {
255+
// Most frequent target wins; ties keep the first-encountered target so the
256+
// output is deterministic on any PHP version.
257+
$best_target = null;
258+
$best_count = 0;
259+
foreach ( $freq as $target => $count ) {
260+
if ( $count > $best_count ) {
261+
$best_target = $target;
262+
$best_count = $count;
263+
}
264+
}
265+
$shift_target[ $token ] = $best_target;
266+
}
267+
$row_shifts = array();
268+
$modal_cells = 0;
269+
foreach ( $emitted as $row_id => $cells ) {
270+
foreach ( $cells as $token => $code ) {
271+
if ( $code > 0 && $code < $state_count && $shift_target[ $token ] === $code ) {
272+
$row_shifts[ $row_id ][] = $token;
273+
unset( $emitted[ $row_id ][ $token ] );
274+
++$modal_cells;
275+
}
276+
}
277+
}
278+
233279
/*
234280
* GOTO: targets cluster by nonterminal, so store the most frequent target per
235281
* nonterminal as the default and per-state exceptions as a sparse nested map.
@@ -255,39 +301,46 @@ function ( $t, $c ) {
255301
}
256302
$goto_default[ $nonterminal ] = $best_target;
257303
}
304+
// Keyed by nonterminal (434 wrappers) rather than by state (1,491): the same
305+
// cells in far fewer enclosing arrays.
258306
$goto_exceptions = array();
259307
for ( $state = 0; $state < $state_count; $state++ ) {
260308
foreach ( $goto[ $state ] ?? array() as $nonterminal => $target ) {
261309
if ( $target !== $goto_default[ $nonterminal ] ) {
262-
$goto_exceptions[ $state ][ $nonterminal ] = $target;
310+
$goto_exceptions[ $nonterminal ][ $state ] = $target;
263311
}
264312
}
265-
if ( isset( $goto_exceptions[ $state ] ) ) {
266-
ksort( $goto_exceptions[ $state ] );
267-
}
268313
}
314+
ksort( $goto_exceptions );
269315

270-
// Per-production metadata: lhs symbol, rhs length, and a name (deduplicated).
271-
$name_index = array();
272-
$names = array();
273-
$rule_name = array();
316+
/*
317+
* Per-production metadata: lhs symbol and rhs length. Rule names need no
318+
* per-production index: Bison numbers the nonterminals contiguously, so the
319+
* names list is ordered by lhs id and a rule's name is names[lhs - lhs_base].
320+
*/
274321
$rule_lhs_ids = array();
275322
$rule_lengths = array();
323+
$lhs_name = array(); // Nonterminal id => name.
276324
foreach ( $rule_len as $rule => $len ) {
277-
$name = $rule_lhs[ $rule ] ?? '?';
278-
if ( ! isset( $name_index[ $name ] ) ) {
279-
$name_index[ $name ] = count( $names );
280-
$names[] = $name;
281-
}
282-
$rule_name[ $rule ] = $name_index[ $name ];
283-
$rule_lhs_ids[ $rule ] = $nonterminal_id[ $name ] ?? 0;
284-
$rule_lengths[ $rule ] = $len;
325+
$name = $rule_lhs[ $rule ] ?? '?';
326+
$rule_lhs_ids[ $rule ] = $nonterminal_id[ $name ] ?? 0;
327+
$rule_lengths[ $rule ] = $len;
328+
$lhs_name[ $nonterminal_id[ $name ] ] = $name;
329+
}
330+
ksort( $lhs_name );
331+
$lhs_base = (int) array_keys( $lhs_name )[0];
332+
$last_lhs = (int) array_keys( $lhs_name )[ count( $lhs_name ) - 1 ];
333+
if ( count( $lhs_name ) !== $last_lhs - $lhs_base + 1 ) {
334+
fwrite( STDERR, "error: nonterminal lhs ids are not contiguous ($lhs_base..$last_lhs vs " . count( $lhs_name ) . " names); the names list cannot be indexed by lhs.\n" );
335+
exit( 1 );
285336
}
337+
$names = array_values( $lhs_name );
286338

287339
/*
288340
* Emit minified plain PHP literals: sequential integer-keyed arrays drop their
289-
* keys, everything else is "key=>value", with no whitespace. This keeps the
290-
* artifact a plain, opcache-internable PHP array while staying compact.
341+
* keys, everything else is "key=>value", with no whitespace, using the short
342+
* array syntax. This keeps the artifact a plain, opcache-internable PHP array
343+
* while staying compact.
291344
*/
292345
$emit = function ( $value ) use ( &$emit ) {
293346
if ( ! is_array( $value ) ) {
@@ -298,47 +351,50 @@ function ( $t, $c ) {
298351
foreach ( $value as $k => $v ) {
299352
$parts[] = ( $sequential ? '' : $k . '=>' ) . $emit( $v );
300353
}
301-
return 'array(' . implode( ',', $parts ) . ')';
354+
return '[' . implode( ',', $parts ) . ']';
302355
};
303356
$emit_names = function ( array $names ) {
304357
$parts = array();
305358
foreach ( $names as $name ) {
306359
$parts[] = "'" . str_replace( array( '\\', "'" ), array( '\\\\', "\\'" ), $name ) . "'";
307360
}
308-
return 'array(' . implode( ',', $parts ) . ')';
361+
return '[' . implode( ',', $parts ) . ']';
309362
};
310363

311364
$sections = array(
312365
"'ns'=>" . $state_count,
313366
"'start'=>0",
314367
"'dollar'=>" . ( $terminal_id['$end'] ?? 0 ),
368+
"'lhs_base'=>" . $lhs_base,
315369
"'rows'=>" . $emit( $emitted ),
370+
"'row_shifts'=>" . $emit( $row_shifts ),
316371
"'row_base'=>" . $emit( $row_base ),
372+
"'shift_target'=>" . $emit( $shift_target ),
317373
"'state_row'=>" . $emit( $state_row ),
318374
"'state_default'=>" . $emit( $state_default ),
319375
"'goto_default'=>" . $emit( $goto_default ),
320376
"'goto_exceptions'=>" . $emit( $goto_exceptions ),
321377
"'rule_lhs'=>" . $emit( $rule_lhs_ids ),
322378
"'rule_len'=>" . $emit( $rule_lengths ),
323-
"'rule_name'=>" . $emit( $rule_name ),
324379
"'names'=>" . $emit_names( $names ),
325380
);
326381

327382
$php = "<?php\n"
328383
. "// THIS FILE IS GENERATED by tools/generate-parse-table.php. DO NOT EDIT.\n"
329384
. "// Source: MySQL Bison grammar (sql/sql_yacc.yy) at $mysql_tag.\n"
330385
. "// phpcs:disable\n"
331-
. 'return array(' . "\n" . implode( ",\n", $sections ) . "\n);\n";
386+
. 'return [' . "\n" . implode( ",\n", $sections ) . "\n];\n";
332387
file_put_contents( $output_path, $php );
333388

334389
fwrite(
335390
STDERR,
336391
sprintf(
337-
"rows=%d (patched=%d), cells stored=%d of %d | goto: %d defaults, %d exceptions | names=%d\n",
392+
"rows=%d (patched=%d), cells stored=%d of %d (%d as modal shifts) | goto: %d defaults, %d exception groups | names=%d\n",
338393
count( $rows ),
339394
count( $row_base ),
340395
$stored_cells,
341396
$total_cells,
397+
$modal_cells,
342398
count( $goto_default ),
343399
count( $goto_exceptions ),
344400
count( $names )

0 commit comments

Comments
 (0)