Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.71% covered (warning)
84.71%
266 / 314
12.50% covered (danger)
12.50%
1 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
JavaScriptMinifier
84.71% covered (warning)
84.71%
266 / 314
12.50% covered (danger)
12.50%
1 / 8
260.08
0.00% covered (danger)
0.00%
0 / 1
 ensureExpandedStates
7.69% covered (danger)
7.69%
2 / 26
0.00% covered (danger)
0.00%
0 / 1
244.31
 minify
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createMinifier
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 createSourceMapState
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 createIdentityMinifier
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getNextNonWhitespaceChar
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
8.06
 minifyInternal
94.35% covered (success)
94.35%
234 / 248
0.00% covered (danger)
0.00%
0 / 1
128.86
 augmentDebugContext
68.75% covered (warning)
68.75%
11 / 16
0.00% covered (danger)
0.00%
0 / 1
11.47
1<?php
2declare( strict_types = 1 );
3
4/**
5 * Copyright 2011 Paul Copperman <paul.copperman@gmail.com>
6 * Copyright 2018 Timo Tijhof
7 * Copyright 2021 Roan Kattouw <roan.kattouw@gmail.com>
8 *
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
12 *
13 *     http://www.apache.org/licenses/LICENSE-2.0
14 *
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 *
21 * @file
22 * @license Apache-2.0
23 * @license MIT
24 * @license GPL-2.0-or-later
25 * @license LGPL-2.1-or-later
26 */
27
28namespace Wikimedia\Minify;
29
30use ReflectionClass;
31
32/**
33 * JavaScript Minifier
34 *
35 * This class is meant to safely minify JavaScript code, while leaving syntactically correct
36 * programs intact. Other libraries, such as JSMin require a certain coding style to work
37 * correctly. OTOH, libraries like jsminplus, that do parse the code correctly are rather
38 * slow, because they construct a complete parse tree before outputting the code minified.
39 * So this class is meant to allow arbitrary (but syntactically correct) input, while being
40 * fast enough to be used for on-the-fly minifying.
41 *
42 * This class was written with the ECMAScript 2025 Language Specification in mind. Parsing features
43 * new to later editions of ECMAScript might not be supported. It's assumed that the input is
44 * syntactically correct; if it's not, this class may not detect that, and may produce incorrect
45 * output.
46 *
47 * See also:
48 * - <https://262.ecma-international.org/16.0/>
49 */
50class JavaScriptMinifier {
51
52    /* Parsing states.
53     * The state machine is necessary to decide whether to parse a slash as division
54     * operator or as regexp literal, and to know where semicolon insertion is possible.
55     * States are generally named after the next expected item. We only distinguish states when the
56     * distinction is relevant for our purpose. The meaning of these states is documented
57     * in $model below.
58     *
59     * Negative numbers are used to indicate that the state is inside a generator function,
60     * which changes the behavior of 'yield'
61     */
62    private const STATEMENT                     = 1;
63    private const CONDITION                     = 2;
64    private const FUNC                          = 3;
65    private const GENFUNC                       = 4;
66    private const PROPERTY_ASSIGNMENT           = 5;
67    private const EXPRESSION                    = 6;
68    private const EXPRESSION_NO_NL              = 7;
69    private const EXPRESSION_OP                 = 8;
70    private const EXPRESSION_DOT                = 9;
71    private const EXPRESSION_END                = 10;
72    private const EXPRESSION_ARROWFUNC          = 11;
73    private const EXPRESSION_TERNARY            = 12;
74    private const EXPRESSION_TERNARY_OP         = 13;
75    private const EXPRESSION_TERNARY_DOT        = 14;
76    private const EXPRESSION_TERNARY_ARROWFUNC  = 15;
77    private const PAREN_EXPRESSION              = 16;
78    private const PAREN_EXPRESSION_OP           = 17;
79    private const PAREN_EXPRESSION_DOT          = 18;
80    private const PAREN_EXPRESSION_ARROWFUNC    = 19;
81    private const PROPERTY_EXPRESSION           = 20;
82    private const PROPERTY_EXPRESSION_OP        = 21;
83    private const PROPERTY_EXPRESSION_DOT       = 22;
84    private const PROPERTY_EXPRESSION_ARROWFUNC = 23;
85    private const CLASS_DEF                     = 24;
86    private const IMPORT_EXPORT                 = 25;
87    private const TEMPLATE_STRING_HEAD          = 26;
88    private const TEMPLATE_STRING_TAIL          = 27;
89    private const PAREN_EXPRESSION_OP_NO_NL     = 28;
90    private const EXPRESSION_TERNARY_NO_NL      = 29;
91    private const PAREN_EXPRESSION_NO_NL        = 30;
92    private const PROPERTY_EXPRESSION_NO_NL     = 31;
93    private const PROPERTY_EXPRESSION_ASYNC     = 32;
94
95    /* Token types */
96
97    /** @var int unary operators */
98    private const TYPE_UN_OP = 101;
99
100    /** @var int ++ and -- */
101    private const TYPE_INCR_OP = 102;
102
103    /** @var int binary operators (except .) */
104    private const TYPE_BIN_OP = 103;
105
106    /** @var int + and - which can be either unary or binary ops */
107    private const TYPE_ADD_OP = 104;
108
109    /** @var int . */
110    private const TYPE_DOT = 105;
111
112    /** @var int ? */
113    private const TYPE_HOOK = 106;
114
115    /** @var int : */
116    private const TYPE_COLON = 107;
117
118    /** @var int , */
119    private const TYPE_COMMA = 108;
120
121    /** @var int ; */
122    private const TYPE_SEMICOLON = 109;
123
124    /** @var int { */
125    private const TYPE_BRACE_OPEN = 110;
126
127    /** @var int } */
128    private const TYPE_BRACE_CLOSE = 111;
129
130    /** @var int ( and [ */
131    private const TYPE_PAREN_OPEN = 112;
132
133    /** @var int ) and ] */
134    private const TYPE_PAREN_CLOSE = 113;
135
136    /** @var int => */
137    private const TYPE_ARROW = 114;
138
139    /** @var int keywords: break, continue, return, throw (and yield, if we're in a generator) */
140    private const TYPE_RETURN = 115;
141
142    /** @var int keywords: catch, for, with, switch, while, if */
143    private const TYPE_IF = 116;
144
145    /** @var int keywords: case, finally, else, do, try */
146    private const TYPE_DO = 117;
147
148    /** @var int keywords: var, let, const */
149    private const TYPE_VAR = 118;
150
151    /** @var int keywords: yield */
152    private const TYPE_YIELD = 119;
153
154    /** @var int keywords: function */
155    private const TYPE_FUNC = 120;
156
157    /** @var int keywords: class */
158    private const TYPE_CLASS = 121;
159
160    /** @var int all literals, identifiers, unrecognised tokens, and other keywords */
161    private const TYPE_LITERAL = 122;
162
163    /** @var int For special treatment of tokens that usually mean something else */
164    private const TYPE_SPECIAL = 123;
165
166    /** @var int keywords: async */
167    private const TYPE_ASYNC = 124;
168
169    /** @var int keywords: await */
170    private const TYPE_AWAIT = 125;
171
172    /** @var int Go to another state */
173    private const ACTION_GOTO = 201;
174
175    /** @var int Push a state to the stack */
176    private const ACTION_PUSH = 202;
177
178    /** @var int Pop the state from the top of the stack, and go to that state */
179    private const ACTION_POP = 203;
180
181    /** @var int Limit to avoid excessive memory usage */
182    private const STACK_LIMIT = 1000;
183
184    /**
185     * @var int $maxLineLength
186     *
187     * Maximum line length
188     *
189     * This is not a strict maximum, but a guideline. Longer lines will be
190     * produced when literals (e.g. quoted strings) longer than this are
191     * encountered, or when required to guard against semicolon insertion.
192     *
193     * This is a private member (instead of constant) to allow tests to
194     * set it to 1, to verify ASI and line-breaking behaviour.
195     */
196    private static $maxLineLength = 1000;
197
198    private static bool $expandedStates = false;
199
200    /**
201     * @var array $opChars
202     *
203     * Characters which can be combined without whitespace between them.
204     * Unlike the ECMAScript spec, we define these as individual symbols, not sequences.
205     */
206    private static $opChars = [
207        // ECMAScript 2025 Â§ 12.8 Punctuators
208        //
209        //    Punctuator
210        //    DivPunctuator
211        //    RightBracePunctuator
212        //
213        '{' => true,
214        '(' => true,
215        ')' => true,
216        '[' => true,
217        ']' => true,
218        // Dots have a special case after $plainDigits which require whitespace
219        '.' => true,
220        ';' => true,
221        ',' => true,
222        '<' => true,
223        '>' => true,
224        '=' => true,
225        '!' => true,
226        '+' => true,
227        '-' => true,
228        '*' => true,
229        '%' => true,
230        '&' => true,
231        '|' => true,
232        '^' => true,
233        '~' => true,
234        '?' => true,
235        ':' => true,
236        '/' => true,
237        '}' => true,
238
239        // ECMAScript 2025 Â§ 12.9.4 String Literals
240        '"' => true,
241        "'" => true,
242
243        // ECMAScript 2025 Â§ 12.9.6 Template Literal Lexical Components
244        '`' => true,
245    ];
246
247    /**
248     * Table-driven lookahead map for parsing multi-character punctuation operators.
249     *
250     * This is the subset of $tokenTypes keys, made of two or more $opChars. It must be
251     * updated whenever punctuation operators are added to $tokenTypes. This is ensured
252     * by the JavaScriptMinifierTest::testOperatorLookaheadCoversAllTokens test case.
253     *
254     * The shape of this map is one character offset per array level (or "column").
255     * The total depth is based on the longest punctuation token in $tokenTypes.
256     * Currently, the longest punctuation token is `>>>=`, which is 4 characters.
257     *
258     * Example:
259     * - Token AB is stored at `['A']['B'][''][''] === 2`,
260     *   Token ABC is stored at `['A']['B']['C'][''] === 3`,
261     *   Token ABCD is stored at `['A']['B']['C']['D'] === 4`
262     * - The parser looks at `map[$ch][$next2][$next3][$next4]`.
263     * - If set, it directly moves past that number of characters to parse the current token.
264     *
265     * We have a fairly even distribution (most starting characters lead to only 1 or 2 possible
266     * tokens), so the most valuable optimization is to look at the first character and narrow
267     * our options, before performing any other potentially unnecessary assignments and lookups.
268     *
269     * The most common token length in this map is 2 (because 3 and 4 are rare, and 1-length tokens
270     * don't need lookahead) and most of those are unambigious (i.e. not the start of a longer
271     * token) which allows for a further optimization. Whenever possible, we store length 2 in
272     * a shortcut directly under `map[$ch][$next2]` instead of `map[$ch][$next2]['']['']`.
273     * This allows the parser to usually stop after 2 lookups (at the cost of an extra isset),
274     * instead of always peforming the worst case (4 lookups) for all operators.
275     */
276    private const MULTICHAR_PUNCTOKENS = [
277        '.' => [
278            '.' => [
279                '.' => [
280                    '' => 3,
281                ],
282            ],
283        ],
284        '+' => [
285            '+' => 2,
286            '=' => 2,
287        ],
288        '-' => [
289            '-' => 2,
290            '=' => 2,
291        ],
292        '*' => [
293            '*' => [
294                '' => 2,
295                '=' => [
296                    '' => 3,
297                ],
298            ],
299            '=' => 2,
300        ],
301        '<' => [
302            '<' => [
303                '' => 2,
304                '=' => [
305                    '' => 3,
306                ],
307            ],
308            '=' => 2,
309        ],
310        '>' => [
311            '>' => [
312                '' => 2,
313                '>' => [
314                    '' => 3,
315                    '=' => 4,
316                ],
317                '=' => [
318                    '' => 3,
319                ],
320                '>=' => 4,
321            ],
322            '=' => 2,
323        ],
324        '=' => [
325            '=' => [
326                '' => 2,
327                '=' => [
328                    '' => 3,
329                ],
330            ],
331            '>' => 2,
332        ],
333        '!' => [
334            '=' => [
335                '' => 2,
336                '=' => [
337                    '' => 3,
338                ],
339            ],
340        ],
341        '&' => [
342            '&' => [
343                '' => 2,
344                '=' => [
345                    '' => 3,
346                ],
347            ],
348            '=' => 2,
349        ],
350        '|' => [
351            '|' => [
352                '' => 2,
353                '=' => [
354                    '' => 3,
355                ],
356            ],
357            '=' => 2,
358        ],
359        '?' => [
360            '?' => [
361                '' => 2,
362                '=' => [
363                    '' => 3,
364                ],
365            ],
366            '.' => 2,
367        ],
368        '/' => [
369            '=' => 2,
370        ],
371        '%' => [
372            '=' => 2,
373        ],
374        '^' => [
375            '=' => 2,
376        ],
377    ];
378
379    /**
380     * @var array $tokenTypes
381     *
382     * Tokens and their types.
383     */
384    private static $tokenTypes = [
385        // Can be one of:
386        //
387        // - ECMAScript 2025 Â§ 13.2.4 Array Initializer
388        //    ... AssignmentExpression
389        // - ECMAScript 2025 Â§ 14.3.3 Destructuring Binding Patterns
390        //    ... BindingIdentifier
391        //    ... BindingPattern
392        '...'        => self::TYPE_UN_OP,
393
394        // ECMAScript 2025 Â§ 13.3 Left-Hand-Side Expressions
395        //
396        //    MemberExpression
397        //    OptionalExpression
398        //
399        // A dot can also be part of a DecimalLiteral, but in that case we handle the entire
400        // DecimalLiteral as one token. A separate '.' token is always part of a MemberExpression.
401        '.'          => self::TYPE_DOT,
402        '?.'         => self::TYPE_DOT,
403
404        // ECMAScript 2025 Â§ 13.4 Update Expressions
405        //
406        //    LeftHandSideExpression [no LineTerminator here] ++
407        //    LeftHandSideExpression [no LineTerminator here] --
408        //    ++ UnaryExpression
409        //    -- UnaryExpression
410        //
411        // This is given a separate type from TYPE_UN_OP,
412        // because `++` and `--` require special handling
413        // around new lines and semicolon insertion.
414        //
415        '++'         => self::TYPE_INCR_OP,
416        '--'         => self::TYPE_INCR_OP,
417
418        // ECMAScript 2025 Â§ 13.5 Unary Operators
419        //
420        //    UnaryExpression
421        //        includes UpdateExpression
422        //            includes LeftHandSideExpression
423        //                includes NewExpression, which defines 'new'
424        //
425        'new'        => self::TYPE_UN_OP,
426        'delete'     => self::TYPE_UN_OP,
427        'void'       => self::TYPE_UN_OP,
428        'typeof'     => self::TYPE_UN_OP,
429        '~'          => self::TYPE_UN_OP,
430        '!'          => self::TYPE_UN_OP,
431
432        // These operators can be either binary or unary depending on context,
433        // and thus require separate type from TYPE_UN_OP and TYPE_BIN_OP.
434        //
435        //     var z = +y;    // unary (convert to number)
436        //     var z = x + y; // binary (add operation)
437        //
438        // ECMAScript 2025 Â§ 13.5 Unary Operators
439        //
440        //     + UnaryExpression
441        //     - UnaryExpression
442        //
443        // ECMAScript 2025 Â§ 13.8 Additive Operators
444        //
445        //     AdditiveExpression + MultiplicativeExpression
446        //     AdditiveExpression - MultiplicativeExpression
447        //
448        '+'          => self::TYPE_ADD_OP,
449        '-'          => self::TYPE_ADD_OP,
450
451        // These operators can be treated the same as binary operators. Their
452        // productions all place an operator token between a left operand and a
453        // right operand, and do not require special handling for preserving
454        // whitespace or line breaks.
455        //
456        // Defined in:
457        // - ECMAScript 2025 Â§ 13.6 Exponentiation Operator
458        //   ExponentiationExpression
459        // - ECMAScript 2025 Â§ 13.7 Multiplicative Operators
460        //   MultiplicativeOperator
461        // - ECMAScript 2025 Â§ 13.9 Bitwise Shift Operators
462        //   ShiftExpression
463        // - ECMAScript 2025 Â§ 13.10 Relational Operators
464        //   RelationalExpression
465        // - ECMAScript 2025 Â§ 13.11 Equality Operators
466        //   EqualityExpression
467        '**'         => self::TYPE_BIN_OP,
468        '*'          => self::TYPE_BIN_OP,
469        '/'          => self::TYPE_BIN_OP,
470        '%'          => self::TYPE_BIN_OP,
471        '<<'         => self::TYPE_BIN_OP,
472        '>>'         => self::TYPE_BIN_OP,
473        '>>>'        => self::TYPE_BIN_OP,
474        '<'          => self::TYPE_BIN_OP,
475        '>'          => self::TYPE_BIN_OP,
476        '<='         => self::TYPE_BIN_OP,
477        '>='         => self::TYPE_BIN_OP,
478        'instanceof' => self::TYPE_BIN_OP,
479        'in'         => self::TYPE_BIN_OP,
480        '=='         => self::TYPE_BIN_OP,
481        '!='         => self::TYPE_BIN_OP,
482        '==='        => self::TYPE_BIN_OP,
483        '!=='        => self::TYPE_BIN_OP,
484
485        // ECMAScript 2025 Â§ 13.12 Binary Bitwise Operators
486        //
487        //    BitwiseANDExpression
488        //    BitwiseXORExpression
489        //    BitwiseORExpression
490        //
491        '&'          => self::TYPE_BIN_OP,
492        '^'          => self::TYPE_BIN_OP,
493        '|'          => self::TYPE_BIN_OP,
494
495        // ECMAScript 2025 Â§ 13.13 Binary Logical Operators
496        //
497        //    LogicalANDExpression
498        //    LogicalORExpression
499        //    CoalesceExpression
500        //
501        //    ShortCircuitExpression
502        //        includes LogicalORExpression
503        //        includes CoalesceExpression
504        //
505        '&&'         => self::TYPE_BIN_OP,
506        '||'         => self::TYPE_BIN_OP,
507        '??'         => self::TYPE_BIN_OP,
508
509        // ECMAScript 2025 Â§ 13.14 Conditional Operator
510        //
511        //    ConditionalExpression:
512        //        ShortCircuitExpression ? AssignmentExpression : AssignmentExpression
513        //
514        // Also known as ternary.
515        '?'          => self::TYPE_HOOK,
516        ':'          => self::TYPE_COLON,
517
518        // ECMAScript 2025 Â§ 13.15 Assignment Operators
519        '='          => self::TYPE_BIN_OP,
520        '*='         => self::TYPE_BIN_OP,
521        '/='         => self::TYPE_BIN_OP,
522        '%='         => self::TYPE_BIN_OP,
523        '+='         => self::TYPE_BIN_OP,
524        '-='         => self::TYPE_BIN_OP,
525        '<<='        => self::TYPE_BIN_OP,
526        '>>='        => self::TYPE_BIN_OP,
527        '>>>='       => self::TYPE_BIN_OP,
528        '&='         => self::TYPE_BIN_OP,
529        '^='         => self::TYPE_BIN_OP,
530        '|='         => self::TYPE_BIN_OP,
531        '**='        => self::TYPE_BIN_OP,
532        '&&='        => self::TYPE_BIN_OP,
533        '||='        => self::TYPE_BIN_OP,
534        '??='        => self::TYPE_BIN_OP,
535
536        // ECMAScript 2025 Â§ 13.16 Comma Operator
537        ','          => self::TYPE_COMMA,
538
539        // ECMAScript 2025 Â§ 12.10.1 Rules of Automatic Semicolon Insertion
540        //
541        // These keywords disallow LineTerminator before their following operand
542        // or label. They are similar enough that we can treat them all the same
543        // way that we treat return, with regards to new line and semicolon insertion.
544        //
545        //     continue [no LineTerminator here] LabelIdentifier ;
546        //     break [no LineTerminator here] LabelIdentifier ;
547        //     return [no LineTerminator here] Expression ;
548        //     throw [no LineTerminator here] Expression ;
549        //     yield [no LineTerminator here] AssignmentExpression ;
550        //     yield [no LineTerminator here] * AssignmentExpression ;
551        //
552        // continue, break, return, and yield also allow the operand or label
553        // to be omitted.
554        //
555        // See also ECMAScript 2025:
556        // - Â§ 14.8 The continue Statement
557        // - Â§ 14.9 The break Statement
558        // - Â§ 14.10 The return Statement
559        // - Â§ 14.14 The throw Statement
560        // - Â§ 15.5 Generator Function Definitions (yield)
561        'continue'   => self::TYPE_RETURN,
562        'break'      => self::TYPE_RETURN,
563        'return'     => self::TYPE_RETURN,
564        'throw'      => self::TYPE_RETURN,
565        // "yield" only counts as a keyword inside generator functions,
566        // otherwise it is a regular identifier.
567        // This is handled with the negative states hack: if the state is negative, TYPE_YIELD
568        // is treated as TYPE_RETURN, if it's positive it's treated as TYPE_LITERAL
569        'yield'      => self::TYPE_YIELD,
570
571        // These keywords start constructs whose header/body shape is close enough
572        // for the minifier to treat them like "if".
573        //
574        // See also ECMAScript 2025:
575        // - Â§ 14.6 The if Statement
576        // - Â§ 14.7 Iteration Statements (while, for)
577        // - Â§ 14.11 The with Statement
578        // - Â§ 14.12 The switch Statement
579        // - Â§ 14.15 The try Statement (catch)
580        'if'         => self::TYPE_IF,
581        'while'      => self::TYPE_IF,
582        'for'        => self::TYPE_IF,
583        'with'       => self::TYPE_IF,
584        'switch'     => self::TYPE_IF,
585        'catch'      => self::TYPE_IF,
586
587        // ECMAScript 2025 Â§ 14.7.5 The for-in, for-of, and for-await-of Statements
588        'of'         => self::TYPE_BIN_OP,
589
590        // These keywords start productions whose next significant token belongs
591        // to a Statement, Expression, or Block. The minifier can treat those
592        // shapes alike.
593        //
594        // See also ECMAScript 2025:
595        // - Â§ 14.6 The if Statement (else)
596        // - Â§ 14.7 Iteration Statements (do)
597        // - Â§ 14.12 The switch Statement (case)
598        // - Â§ 14.15 The try Statement (try, finally)
599        'else'       => self::TYPE_DO,
600        'do'         => self::TYPE_DO,
601        'case'       => self::TYPE_DO,
602        'try'        => self::TYPE_DO,
603        'finally'    => self::TYPE_DO,
604
605        // ECMAScript 2025 Â§ 14.3 Declarations and the Variable Statement
606        //
607        //    LetOrConst
608        //    VariableStatement
609        //
610        // These keywords are followed by a variable declaration statement.
611        // This needs to be treated differently from the TYPE_DO group,
612        // because for TYPE_VAR, when we see an "{" open curly brace, it
613        // begins object destructuring (ObjectBindingPattern), not a block.
614        'var'        => self::TYPE_VAR,
615        'let'        => self::TYPE_VAR,
616        'const'      => self::TYPE_VAR,
617
618        // ECMAScript 2025 Â§ 15.2 Function Definitions
619        'function'   => self::TYPE_FUNC,
620
621        // ECMAScript 2025 Â§ 15.3 Arrow Function Definitions
622        '=>'         => self::TYPE_ARROW,
623
624        // ECMAScript 2025 Â§ 15.7 Class Definitions
625        //
626        //     ClassDeclaration:
627        //         class BindingIdentifier ClassTail
628        //         class ClassTail
629        //     ClassExpression:
630        //         class BindingIdentifier? ClassTail
631        //     ClassTail:
632        //         ClassHeritage? { ClassBody? }
633        //     ClassHeritage:
634        //         extends LeftHandSideExpression
635        //
636        'class'      => self::TYPE_CLASS,
637
638        // ECMAScript 2025 Â§ 15.8 Async Function Definitions
639        //
640        //     AwaitExpression:
641        //         await UnaryExpression
642        //
643        'await'      => self::TYPE_AWAIT,
644
645        // Can be one of:
646        // - Block (ECMAScript 2025 Â§ 14.2 Block)
647        // - ObjectLiteral (ECMAScript 2025 Â§ 13.2 Primary Expression)
648        '{'          => self::TYPE_BRACE_OPEN,
649        '}'          => self::TYPE_BRACE_CLOSE,
650
651        // Can be one of:
652        // - Parenthesized header after a TYPE_IF keyword or parameter list
653        //   after a TYPE_FUNC keyword.
654        // - PrimaryExpression (ECMAScript 2025 Â§ 13.2 Primary Expression)
655        // - CallExpression (ECMAScript 2025 Â§ 13.3 Left-Hand-Side Expressions)
656        // - Beginning of an ArrowFunction (ECMAScript 2025 Â§ 15.3 Arrow Function Definitions)
657        '('          => self::TYPE_PAREN_OPEN,
658        ')'          => self::TYPE_PAREN_CLOSE,
659
660        // Can be one of:
661        // - ArrayLiteral (ECMAScript 2025 Â§ 13.2 Primary Expression)
662        // - ComputedPropertyName (ECMAScript 2025 Â§ 13.2.5 Object Initializer)
663        '['          => self::TYPE_PAREN_OPEN,
664        ']'          => self::TYPE_PAREN_CLOSE,
665
666        // Can be one of:
667        // - End of any statement
668        // - EmptyStatement (ECMAScript 2025 Â§ 14.4 Empty Statement)
669        ';'          => self::TYPE_SEMICOLON,
670
671        // ECMAScript 2025 Â§ 15.8 Async Function Definitions
672        // AsyncFunctionDeclaration starts with:
673        //     async [no LineTerminator here] function
674        // AsyncMethod starts with:
675        //     async [no LineTerminator here] PropertyName or ClassElementName
676        'async'      => self::TYPE_ASYNC,
677    ];
678
679    /**
680     * @var array $model
681     *
682     * The main table for the state machine. Defines the desired action for every state/token pair.
683     *
684     * The state pushed onto the stack by ACTION_PUSH will be returned to by ACTION_POP.
685     * A state/token pair may not specify both ACTION_POP and ACTION_GOTO. If that does happen,
686     * ACTION_POP takes precedence.
687     *
688     * This table is augmented by self::ensureExpandedStates().
689     */
690    private static $model = [
691        // Statement - This is the initial state.
692        self::STATEMENT => [
693            self::TYPE_UN_OP => [
694                self::ACTION_GOTO => self::EXPRESSION,
695            ],
696            self::TYPE_INCR_OP => [
697                self::ACTION_GOTO => self::EXPRESSION,
698            ],
699            self::TYPE_ADD_OP => [
700                self::ACTION_GOTO => self::EXPRESSION,
701            ],
702            self::TYPE_BRACE_OPEN => [
703                // Use of '{' in statement context, creates a Block.
704                self::ACTION_PUSH => self::STATEMENT,
705            ],
706            self::TYPE_BRACE_CLOSE => [
707                // Ends a Block
708                self::ACTION_POP => true,
709            ],
710            self::TYPE_PAREN_OPEN => [
711                self::ACTION_PUSH => self::EXPRESSION_OP,
712                self::ACTION_GOTO => self::PAREN_EXPRESSION,
713            ],
714            self::TYPE_RETURN => [
715                self::ACTION_GOTO => self::EXPRESSION_NO_NL,
716            ],
717            self::TYPE_IF => [
718                self::ACTION_GOTO => self::CONDITION,
719            ],
720            self::TYPE_VAR => [
721                self::ACTION_GOTO => self::EXPRESSION,
722            ],
723            self::TYPE_FUNC => [
724                self::ACTION_PUSH => self::STATEMENT,
725                self::ACTION_GOTO => self::FUNC,
726            ],
727            self::TYPE_CLASS => [
728                self::ACTION_PUSH => self::STATEMENT,
729                self::ACTION_GOTO => self::CLASS_DEF,
730            ],
731            self::TYPE_SPECIAL => [
732                'import' => [
733                    self::ACTION_GOTO => self::IMPORT_EXPORT,
734                ],
735                'export' => [
736                    self::ACTION_GOTO => self::IMPORT_EXPORT,
737                ],
738            ],
739            self::TYPE_LITERAL => [
740                self::ACTION_GOTO => self::EXPRESSION_OP,
741            ],
742            self::TYPE_ASYNC => [
743                self::ACTION_GOTO => self::EXPRESSION_OP,
744            ],
745            self::TYPE_AWAIT => [
746                self::ACTION_GOTO => self::EXPRESSION,
747            ],
748        ],
749        // The state after if/catch/while/for/switch/with
750        // Waits for an expression in parentheses, then goes to STATEMENT
751        self::CONDITION => [
752            self::TYPE_PAREN_OPEN => [
753                self::ACTION_PUSH => self::STATEMENT,
754                self::ACTION_GOTO => self::PAREN_EXPRESSION,
755            ],
756            self::TYPE_BRACE_OPEN => [
757                self::ACTION_PUSH => self::STATEMENT,
758                self::ACTION_GOTO => self::STATEMENT,
759            ]
760        ],
761        // The state after the function keyword. Waits for {, then goes to STATEMENT.
762        // The function body's closing } will pop the stack, so the state to return to
763        // after the function should be pushed to the stack first
764        self::FUNC => [
765            // Needed to prevent * in an expression in the argument list from improperly
766            // triggering GENFUNC
767            self::TYPE_PAREN_OPEN => [
768                self::ACTION_PUSH => self::FUNC,
769                self::ACTION_GOTO => self::PAREN_EXPRESSION,
770            ],
771            self::TYPE_BRACE_OPEN => [
772                self::ACTION_GOTO => self::STATEMENT,
773            ],
774            self::TYPE_SPECIAL => [
775                '*' => [
776                    self::ACTION_GOTO => self::GENFUNC,
777                ],
778            ],
779        ],
780        // State after `function*` to wait for `{` and go to generator function statement.
781        //
782        // For example: `function* myGen(a, b) { yield 1; }`
783        self::GENFUNC => [
784            self::TYPE_BRACE_OPEN => [
785                // Note negative value: generator function states are negative
786                self::ACTION_GOTO => -self::STATEMENT
787            ],
788        ],
789        // State after `{` expecting property keys in an object literal declaration.
790        //
791        // For example: `{ key: value, key2, [computedKey3]: value3, method4() { ... } }`
792        self::PROPERTY_ASSIGNMENT => [
793            // Note that keywords like "if", "class", "var", "delete", "async", etc, are
794            // valid key names, and should be treated as literals here. Like in EXPRESSION_DOT.
795            // For this state, this requires no special handling because TYPE_LITERAL
796            // has no action here, so we remain in this state.
797            //
798            // If this state ever gets a transition for TYPE_LITERAL, then that same transition
799            // must apply to TYPE_IF, TYPE_CLASS, TYPE_VAR, TYPE_ASYNC, etc as well.
800            self::TYPE_COLON => [
801                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
802            ],
803            // For {, which begins a method
804            self::TYPE_BRACE_OPEN => [
805                self::ACTION_PUSH => self::PROPERTY_ASSIGNMENT,
806                // This is not flipped, see "Special cases" below
807                self::ACTION_GOTO => self::STATEMENT,
808            ],
809            self::TYPE_BRACE_CLOSE => [
810                self::ACTION_POP => true,
811            ],
812            // For [, which begins a computed key
813            self::TYPE_PAREN_OPEN => [
814                self::ACTION_PUSH => self::PROPERTY_ASSIGNMENT,
815                self::ACTION_GOTO => self::PAREN_EXPRESSION,
816            ],
817            self::TYPE_SPECIAL => [
818                '*' => [
819                    self::ACTION_PUSH => self::PROPERTY_ASSIGNMENT,
820                    self::ACTION_GOTO => self::GENFUNC,
821                ],
822            ],
823        ],
824        // Place in an expression where we expect an operand or a unary operator: the start
825        // of an expression or after an operator. Note that unary operators (including INCR_OP
826        // and ADD_OP) cause us to stay in this state, while operands take us to EXPRESSION_OP
827        self::EXPRESSION => [
828            self::TYPE_SEMICOLON => [
829                self::ACTION_GOTO => self::STATEMENT,
830            ],
831            self::TYPE_BRACE_OPEN => [
832                self::ACTION_PUSH => self::EXPRESSION_OP,
833                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
834            ],
835            self::TYPE_BRACE_CLOSE => [
836                self::ACTION_POP => true,
837            ],
838            self::TYPE_PAREN_OPEN => [
839                self::ACTION_PUSH => self::EXPRESSION_OP,
840                self::ACTION_GOTO => self::PAREN_EXPRESSION,
841            ],
842            self::TYPE_FUNC => [
843                self::ACTION_PUSH => self::EXPRESSION_OP,
844                self::ACTION_GOTO => self::FUNC,
845            ],
846            self::TYPE_CLASS => [
847                self::ACTION_PUSH => self::EXPRESSION_OP,
848                self::ACTION_GOTO => self::CLASS_DEF,
849            ],
850            self::TYPE_LITERAL => [
851                self::ACTION_GOTO => self::EXPRESSION_OP,
852            ],
853            self::TYPE_ASYNC => [
854                self::ACTION_GOTO => self::EXPRESSION_OP,
855            ],
856            // 'return' can't appear here, but 'yield' can
857            self::TYPE_RETURN => [
858                self::ACTION_GOTO => self::EXPRESSION_NO_NL,
859            ],
860        ],
861
862        // State after `return` (or throw/break/continue/yield) where a newline is not allowed.
863        //
864        // This state is identical to EXPRESSION, except that semicolon insertion can happen here,
865        // and we (almost) never stay here:
866        // in cases where EXPRESSION would do nothing, we go back to EXPRESSION.
867        //
868        // We only stay here if there's a double yield, because `yield yield foo` is valid.
869        self::EXPRESSION_NO_NL => [
870            self::TYPE_UN_OP => [
871                self::ACTION_GOTO => self::EXPRESSION,
872            ],
873            self::TYPE_INCR_OP => [
874                self::ACTION_GOTO => self::EXPRESSION,
875            ],
876            // BIN_OP seems impossible at the start of an expression, but it can happen in
877            // yield *foo
878            self::TYPE_BIN_OP => [
879                self::ACTION_GOTO => self::EXPRESSION,
880            ],
881            self::TYPE_ADD_OP => [
882                self::ACTION_GOTO => self::EXPRESSION,
883            ],
884            self::TYPE_SEMICOLON => [
885                self::ACTION_GOTO => self::STATEMENT,
886            ],
887            self::TYPE_BRACE_OPEN => [
888                self::ACTION_PUSH => self::EXPRESSION_OP,
889                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
890            ],
891            self::TYPE_BRACE_CLOSE => [
892                self::ACTION_POP => true,
893            ],
894            self::TYPE_PAREN_OPEN => [
895                self::ACTION_PUSH => self::EXPRESSION_OP,
896                self::ACTION_GOTO => self::PAREN_EXPRESSION,
897            ],
898            self::TYPE_FUNC => [
899                self::ACTION_PUSH => self::EXPRESSION_OP,
900                self::ACTION_GOTO => self::FUNC,
901            ],
902            self::TYPE_CLASS => [
903                self::ACTION_PUSH => self::EXPRESSION_OP,
904                self::ACTION_GOTO => self::CLASS_DEF,
905            ],
906            self::TYPE_LITERAL => [
907                self::ACTION_GOTO => self::EXPRESSION_OP,
908            ],
909            self::TYPE_ASYNC => [
910                self::ACTION_GOTO => self::EXPRESSION_OP,
911            ],
912            self::TYPE_AWAIT => [
913                self::ACTION_GOTO => self::EXPRESSION,
914            ],
915            // 'return' can't appear here, because 'return return' isn't allowed
916            // But 'yield' can appear here, because 'yield yield' is allowed
917            self::TYPE_RETURN => [
918                self::ACTION_GOTO => self::EXPRESSION_NO_NL,
919            ],
920        ],
921
922        // State after an literal or operand in an expression, such as:
923        // `var x = foo`      potentially `var x = foo + 1` or `var x = foo()`
924        // `var x = async`    potentially `var x = async + 1` or `var x = async function () {}`
925        //
926        // This is also the state we pop back to after a nested operation has
927        // completed such as after:
928        // `var x = (foo + 1)`
929        // `var x = { foo: 1 }`
930        // `var x = class Foo {}`
931        // `var x = function () {}`
932        //
933        // We are in an expression after an operand, and expect an operator
934        self::EXPRESSION_OP => [
935            self::TYPE_BIN_OP => [
936                self::ACTION_GOTO => self::EXPRESSION,
937            ],
938            self::TYPE_ADD_OP => [
939                self::ACTION_GOTO => self::EXPRESSION,
940            ],
941            self::TYPE_DOT => [
942                self::ACTION_GOTO => self::EXPRESSION_DOT,
943            ],
944            self::TYPE_HOOK => [
945                self::ACTION_PUSH => self::EXPRESSION,
946                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
947            ],
948            self::TYPE_COLON => [
949                self::ACTION_GOTO => self::STATEMENT,
950            ],
951            self::TYPE_COMMA => [
952                self::ACTION_GOTO => self::EXPRESSION,
953            ],
954            self::TYPE_SEMICOLON => [
955                self::ACTION_GOTO => self::STATEMENT,
956            ],
957            self::TYPE_ARROW => [
958                self::ACTION_GOTO => self::EXPRESSION_ARROWFUNC,
959            ],
960            self::TYPE_PAREN_OPEN => [
961                self::ACTION_PUSH => self::EXPRESSION_OP,
962                self::ACTION_GOTO => self::PAREN_EXPRESSION,
963            ],
964            self::TYPE_BRACE_CLOSE => [
965                self::ACTION_POP => true,
966            ],
967            self::TYPE_FUNC => [
968                self::ACTION_PUSH => self::EXPRESSION_OP,
969                self::ACTION_GOTO => self::FUNC,
970            ],
971        ],
972
973        // State after a dot in EXPRESSION_OP, such as:
974        // `var x = foo.`
975        // `var x = (foo + 1).`
976        //
977        // Like EXPRESSION, except many keywords behave like literals
978        // (e.g. class, if, else, var, function) because they're not valid as identifiers
979        // but are valid as property names.
980        self::EXPRESSION_DOT => [
981            self::TYPE_LITERAL => [
982                self::ACTION_GOTO => self::EXPRESSION_OP,
983            ],
984            // The following are keywords behaving as literals
985            self::TYPE_ASYNC => [
986                self::ACTION_GOTO => self::EXPRESSION_OP,
987            ],
988            self::TYPE_RETURN => [
989                self::ACTION_GOTO => self::EXPRESSION_OP,
990            ],
991            self::TYPE_IF => [
992                self::ACTION_GOTO => self::EXPRESSION_OP,
993            ],
994            self::TYPE_DO => [
995                self::ACTION_GOTO => self::EXPRESSION_OP,
996            ],
997            self::TYPE_VAR => [
998                self::ACTION_GOTO => self::EXPRESSION_OP,
999            ],
1000            self::TYPE_FUNC => [
1001                self::ACTION_GOTO => self::EXPRESSION_OP,
1002            ],
1003            self::TYPE_CLASS => [
1004                self::ACTION_GOTO => self::EXPRESSION_OP,
1005            ],
1006            // We don't expect real unary/binary operators here, but some keywords
1007            // (new, delete, void, typeof, instanceof, in) are classified as such, and they can be
1008            // used as property names
1009            self::TYPE_UN_OP => [
1010                self::ACTION_GOTO => self::EXPRESSION_OP,
1011            ],
1012            self::TYPE_BIN_OP => [
1013                self::ACTION_GOTO => self::EXPRESSION_OP,
1014            ],
1015            self::TYPE_PAREN_OPEN => [
1016                self::ACTION_PUSH => self::EXPRESSION_OP,
1017                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1018            ],
1019        ],
1020
1021        // State after the `}` that closes an arrow function body
1022        //
1023        // Like STATEMENT except it allows semicolon insertion, COMMA can continue the expression,
1024        // and after a function we go to STATEMENT instead of EXPRESSION_OP.
1025        self::EXPRESSION_END => [
1026            self::TYPE_UN_OP => [
1027                self::ACTION_GOTO => self::EXPRESSION,
1028            ],
1029            self::TYPE_INCR_OP => [
1030                self::ACTION_GOTO => self::EXPRESSION,
1031            ],
1032            self::TYPE_ADD_OP => [
1033                self::ACTION_GOTO => self::EXPRESSION,
1034            ],
1035            self::TYPE_COMMA => [
1036                self::ACTION_GOTO => self::EXPRESSION,
1037            ],
1038            self::TYPE_SEMICOLON => [
1039                self::ACTION_GOTO => self::STATEMENT,
1040            ],
1041            self::TYPE_BRACE_OPEN => [
1042                self::ACTION_PUSH => self::STATEMENT,
1043                self::ACTION_GOTO => self::STATEMENT,
1044            ],
1045            self::TYPE_BRACE_CLOSE => [
1046                self::ACTION_POP => true,
1047            ],
1048            self::TYPE_PAREN_OPEN => [
1049                self::ACTION_PUSH => self::EXPRESSION_OP,
1050                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1051            ],
1052            self::TYPE_RETURN => [
1053                self::ACTION_GOTO => self::EXPRESSION_NO_NL,
1054            ],
1055            self::TYPE_IF => [
1056                self::ACTION_GOTO => self::CONDITION,
1057            ],
1058            self::TYPE_VAR => [
1059                self::ACTION_GOTO => self::EXPRESSION,
1060            ],
1061            self::TYPE_FUNC => [
1062                self::ACTION_PUSH => self::STATEMENT,
1063                self::ACTION_GOTO => self::FUNC,
1064            ],
1065            self::TYPE_CLASS => [
1066                self::ACTION_PUSH => self::STATEMENT,
1067                self::ACTION_GOTO => self::CLASS_DEF,
1068            ],
1069            self::TYPE_LITERAL => [
1070                self::ACTION_GOTO => self::EXPRESSION_OP,
1071            ],
1072            self::TYPE_ASYNC => [
1073                self::ACTION_GOTO => self::EXPRESSION_OP,
1074            ],
1075        ],
1076
1077        // State after `=>` such as:
1078        // `var inc = a =>`        potentially `var inc = a => a + 1;`
1079        // `var sum = (a, b) =>`   potentially `var sum = (a, b) => a + b;`
1080        //
1081        // Like EXPRESSION, except that `{` begins an arrow function body
1082        // rather than an object literal.
1083        self::EXPRESSION_ARROWFUNC => [
1084            self::TYPE_UN_OP => [
1085                self::ACTION_GOTO => self::EXPRESSION,
1086            ],
1087            self::TYPE_INCR_OP => [
1088                self::ACTION_GOTO => self::EXPRESSION,
1089            ],
1090            self::TYPE_ADD_OP => [
1091                self::ACTION_GOTO => self::EXPRESSION,
1092            ],
1093            self::TYPE_BRACE_OPEN => [
1094                self::ACTION_PUSH => self::EXPRESSION_END,
1095                self::ACTION_GOTO => self::STATEMENT,
1096            ],
1097            self::TYPE_PAREN_OPEN => [
1098                self::ACTION_PUSH => self::EXPRESSION_OP,
1099                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1100            ],
1101            self::TYPE_FUNC => [
1102                self::ACTION_PUSH => self::EXPRESSION_OP,
1103                self::ACTION_GOTO => self::FUNC,
1104            ],
1105            self::TYPE_CLASS => [
1106                self::ACTION_PUSH => self::EXPRESSION_OP,
1107                self::ACTION_GOTO => self::CLASS_DEF,
1108            ],
1109            self::TYPE_LITERAL => [
1110                self::ACTION_GOTO => self::EXPRESSION_OP,
1111            ],
1112        ],
1113
1114        // State after `?` in EXPRESSION_OP, expecting another expression, such as:
1115        // `var x = foo ?`
1116        // `foo ?`
1117        //
1118        // This differs from EXPRESSION because a `:` ends the ternary
1119        // rather than starting STATEMENT (outside a ternary, `:` comes after a goto label)
1120        // The actual rule for `:` ending the ternary is in EXPRESSION_TERNARY_OP.
1121        self::EXPRESSION_TERNARY => [
1122            self::TYPE_BRACE_OPEN => [
1123                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1124                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1125            ],
1126            self::TYPE_PAREN_OPEN => [
1127                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1128                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1129            ],
1130            self::TYPE_FUNC => [
1131                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1132                self::ACTION_GOTO => self::FUNC,
1133            ],
1134            self::TYPE_CLASS => [
1135                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1136                self::ACTION_GOTO => self::CLASS_DEF,
1137            ],
1138            self::TYPE_LITERAL => [
1139                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1140            ],
1141            // 'return' can't appear here, but 'yield' can
1142            self::TYPE_RETURN => [
1143                self::ACTION_GOTO => self::EXPRESSION_TERNARY_NO_NL,
1144            ],
1145        ],
1146        // Like EXPRESSION_TERNARY, except that semicolon insertion can happen
1147        // See also EXPRESSION_NO_NL
1148        self::EXPRESSION_TERNARY_NO_NL => [
1149            self::TYPE_BRACE_OPEN => [
1150                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1151                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1152            ],
1153            self::TYPE_PAREN_OPEN => [
1154                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1155                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1156            ],
1157            self::TYPE_FUNC => [
1158                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1159                self::ACTION_GOTO => self::FUNC,
1160            ],
1161            self::TYPE_CLASS => [
1162                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1163                self::ACTION_GOTO => self::CLASS_DEF,
1164            ],
1165            self::TYPE_LITERAL => [
1166                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1167            ],
1168            // 'yield' can appear here, because 'yield yield' is allowed
1169            self::TYPE_RETURN => [
1170                self::ACTION_GOTO => self::EXPRESSION_TERNARY_NO_NL,
1171            ],
1172            self::TYPE_UN_OP => [
1173                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1174            ],
1175            self::TYPE_INCR_OP => [
1176                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1177            ],
1178            // BIN_OP seems impossible at the start of an expression, but it can happen in
1179            // yield *foo
1180            self::TYPE_BIN_OP => [
1181                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1182            ],
1183            self::TYPE_ADD_OP => [
1184                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1185            ],
1186        ],
1187
1188        // State after an literal or operand in a ternary expression, such as:
1189        // `var x = foo ? foo`       potentially `foo ? foo + 1 : 0` or `foo ? foo.bar : 0`
1190        //
1191        // This is also the state we pop back to after a nested operation has
1192        // completed such as after:
1193        // `var x = foo ? (foo + 1)`
1194        // `var x = foo ? { foo: 1 }`
1195        // `var x = foo ? function (a, b) {}`
1196        //
1197        // Like EXPRESSION_OP, but for ternaries, see EXPRESSION_TERNARY
1198        self::EXPRESSION_TERNARY_OP => [
1199            self::TYPE_BIN_OP => [
1200                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1201            ],
1202            self::TYPE_ADD_OP => [
1203                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1204            ],
1205            self::TYPE_DOT => [
1206                self::ACTION_GOTO => self::EXPRESSION_TERNARY_DOT,
1207            ],
1208            self::TYPE_HOOK => [
1209                self::ACTION_PUSH => self::EXPRESSION_TERNARY,
1210                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1211            ],
1212            self::TYPE_COMMA => [
1213                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1214            ],
1215            self::TYPE_ARROW => [
1216                self::ACTION_GOTO => self::EXPRESSION_TERNARY_ARROWFUNC,
1217            ],
1218            self::TYPE_PAREN_OPEN => [
1219                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1220                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1221            ],
1222            self::TYPE_COLON => [
1223                self::ACTION_POP => true,
1224            ],
1225        ],
1226
1227        // State after a dot in a ternary expression, such as:
1228        // `var x = foo ? foo.`
1229        // `var x = foo ? (foo + 1).`
1230        //
1231        // Like EXPRESSION_DOT, but for ternaries, see EXPRESSION_TERNARY
1232        self::EXPRESSION_TERNARY_DOT => [
1233            self::TYPE_LITERAL => [
1234                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1235            ],
1236            // The following are keywords behaving as literals
1237            self::TYPE_ASYNC => [
1238                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1239            ],
1240            self::TYPE_RETURN => [
1241                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1242            ],
1243            self::TYPE_IF => [
1244                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1245            ],
1246            self::TYPE_DO => [
1247                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1248            ],
1249            self::TYPE_VAR => [
1250                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1251            ],
1252            self::TYPE_FUNC => [
1253                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1254            ],
1255            self::TYPE_CLASS => [
1256                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1257            ],
1258            // We don't expect real unary/binary operators here, but some keywords
1259            // (new, delete, void, typeof, instanceof, in) are classified as such, and they can be
1260            // used as property names
1261            self::TYPE_UN_OP => [
1262                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1263            ],
1264            self::TYPE_BIN_OP => [
1265                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1266            ],
1267            self::TYPE_PAREN_OPEN => [
1268                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1269                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1270            ],
1271        ],
1272        // Like EXPRESSION_ARROWFUNC, but for ternaries, see EXPRESSION_TERNARY
1273        self::EXPRESSION_TERNARY_ARROWFUNC => [
1274            self::TYPE_UN_OP => [
1275                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1276            ],
1277            self::TYPE_INCR_OP => [
1278                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1279            ],
1280            self::TYPE_ADD_OP => [
1281                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1282            ],
1283            self::TYPE_BRACE_OPEN => [
1284                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1285                self::ACTION_GOTO => self::STATEMENT,
1286            ],
1287            self::TYPE_PAREN_OPEN => [
1288                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1289                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1290            ],
1291            self::TYPE_FUNC => [
1292                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1293                self::ACTION_GOTO => self::FUNC,
1294            ],
1295            self::TYPE_CLASS => [
1296                self::ACTION_PUSH => self::EXPRESSION_TERNARY_OP,
1297                self::ACTION_GOTO => self::CLASS_DEF,
1298            ],
1299            self::TYPE_LITERAL => [
1300                self::ACTION_GOTO => self::EXPRESSION_TERNARY_OP,
1301            ],
1302        ],
1303        // Expression inside parentheses. Like EXPRESSION, except that `)` ends this state
1304        // This differs from EXPRESSION because semicolon insertion can't happen here
1305        self::PAREN_EXPRESSION => [
1306            self::TYPE_BRACE_OPEN => [
1307                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1308                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1309            ],
1310            self::TYPE_PAREN_OPEN => [
1311                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1312                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1313            ],
1314            self::TYPE_PAREN_CLOSE => [
1315                self::ACTION_POP => true,
1316            ],
1317            self::TYPE_FUNC => [
1318                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1319                self::ACTION_GOTO => self::FUNC,
1320            ],
1321            self::TYPE_CLASS => [
1322                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1323                self::ACTION_GOTO => self::CLASS_DEF,
1324            ],
1325            self::TYPE_LITERAL => [
1326                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1327            ],
1328            self::TYPE_ASYNC => [
1329                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP_NO_NL,
1330            ],
1331            // 'return' can't appear here, but 'yield' can
1332            self::TYPE_RETURN => [
1333                self::ACTION_GOTO => self::PAREN_EXPRESSION_NO_NL,
1334            ],
1335        ],
1336        // Like PAREN_EXPRESSION, except that semicolon insertion can happen
1337        // See also EXPRESSION_NO_NL
1338        self::PAREN_EXPRESSION_NO_NL => [
1339            self::TYPE_BRACE_OPEN => [
1340                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1341                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1342            ],
1343            self::TYPE_PAREN_OPEN => [
1344                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1345                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1346            ],
1347            self::TYPE_PAREN_CLOSE => [
1348                self::ACTION_POP => true,
1349            ],
1350            self::TYPE_FUNC => [
1351                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1352                self::ACTION_GOTO => self::FUNC,
1353            ],
1354            self::TYPE_CLASS => [
1355                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1356                self::ACTION_GOTO => self::CLASS_DEF,
1357            ],
1358            self::TYPE_LITERAL => [
1359                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1360            ],
1361            self::TYPE_ASYNC => [
1362                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP_NO_NL,
1363            ],
1364            // 'yield' can appear here, because 'yield yield' is allowed
1365            self::TYPE_RETURN => [
1366                self::ACTION_GOTO => self::PAREN_EXPRESSION_NO_NL,
1367            ],
1368            self::TYPE_UN_OP => [
1369                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1370            ],
1371            self::TYPE_INCR_OP => [
1372                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1373            ],
1374            // BIN_OP seems impossible at the start of an expression, but it can happen in
1375            // yield *foo
1376            self::TYPE_BIN_OP => [
1377                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1378            ],
1379            self::TYPE_ADD_OP => [
1380                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1381            ],
1382            self::TYPE_AWAIT => [
1383                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1384            ],
1385        ],
1386        // Like EXPRESSION_OP, but in parentheses, see PAREN_EXPRESSION
1387        self::PAREN_EXPRESSION_OP => [
1388            self::TYPE_BIN_OP => [
1389                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1390            ],
1391            self::TYPE_ADD_OP => [
1392                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1393            ],
1394            self::TYPE_DOT => [
1395                self::ACTION_GOTO => self::PAREN_EXPRESSION_DOT,
1396            ],
1397            self::TYPE_HOOK => [
1398                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1399            ],
1400            self::TYPE_COLON => [
1401                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1402            ],
1403            self::TYPE_COMMA => [
1404                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1405            ],
1406            self::TYPE_SEMICOLON => [
1407                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1408            ],
1409            self::TYPE_ARROW => [
1410                self::ACTION_GOTO => self::PAREN_EXPRESSION_ARROWFUNC,
1411            ],
1412            self::TYPE_PAREN_OPEN => [
1413                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1414                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1415            ],
1416            self::TYPE_PAREN_CLOSE => [
1417                self::ACTION_POP => true,
1418            ],
1419        ],
1420
1421        // State after dot in PAREN_EXPRESSION, such as
1422        // `var x = (foo.`
1423        // `if (foo.`
1424        //
1425        // Like EXPRESSION_DOT, but in parentheses, see PAREN_EXPRESSION
1426        self::PAREN_EXPRESSION_DOT => [
1427            self::TYPE_LITERAL => [
1428                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1429            ],
1430            // The following are keywords behaving as literals
1431            self::TYPE_ASYNC => [
1432                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1433            ],
1434            self::TYPE_RETURN => [
1435                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1436            ],
1437            self::TYPE_IF => [
1438                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1439            ],
1440            self::TYPE_DO => [
1441                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1442            ],
1443            self::TYPE_VAR => [
1444                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1445            ],
1446            self::TYPE_FUNC => [
1447                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1448            ],
1449            self::TYPE_CLASS => [
1450                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1451            ],
1452            // We don't expect real unary/binary operators here, but some keywords
1453            // (new, delete, void, typeof, instanceof, in) are classified as such, and they can be
1454            // used as property names
1455            self::TYPE_UN_OP => [
1456                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1457            ],
1458            self::TYPE_BIN_OP => [
1459                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1460            ],
1461            self::TYPE_PAREN_OPEN => [
1462                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1463                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1464            ],
1465        ],
1466        // Like EXPRESSION_ARROWFUNC, but in parentheses, see PAREN_EXPRESSION
1467        self::PAREN_EXPRESSION_ARROWFUNC => [
1468            self::TYPE_UN_OP => [
1469                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1470            ],
1471            self::TYPE_INCR_OP => [
1472                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1473            ],
1474            self::TYPE_ADD_OP => [
1475                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1476            ],
1477            self::TYPE_BRACE_OPEN => [
1478                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1479                self::ACTION_GOTO => self::STATEMENT,
1480            ],
1481            self::TYPE_PAREN_OPEN => [
1482                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1483                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1484            ],
1485            self::TYPE_FUNC => [
1486                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1487                self::ACTION_GOTO => self::FUNC,
1488            ],
1489            self::TYPE_CLASS => [
1490                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1491                self::ACTION_GOTO => self::CLASS_DEF,
1492            ],
1493            self::TYPE_LITERAL => [
1494                self::ACTION_GOTO => self::PAREN_EXPRESSION_OP,
1495            ],
1496        ],
1497
1498        // Like PAREN_EXPRESSION_OP, for the state after "async" in a PAREN_EXPRESSION,
1499        // for use by the $semicolon model.
1500        self::PAREN_EXPRESSION_OP_NO_NL => [
1501            self::TYPE_BIN_OP => [
1502                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1503            ],
1504            self::TYPE_ADD_OP => [
1505                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1506            ],
1507            self::TYPE_DOT => [
1508                self::ACTION_GOTO => self::PAREN_EXPRESSION_DOT,
1509            ],
1510            self::TYPE_HOOK => [
1511                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1512            ],
1513            self::TYPE_COLON => [
1514                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1515            ],
1516            self::TYPE_COMMA => [
1517                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1518            ],
1519            self::TYPE_SEMICOLON => [
1520                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1521            ],
1522            self::TYPE_ARROW => [
1523                self::ACTION_GOTO => self::PAREN_EXPRESSION_ARROWFUNC,
1524            ],
1525            self::TYPE_PAREN_OPEN => [
1526                self::ACTION_PUSH => self::PAREN_EXPRESSION_OP,
1527                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1528            ],
1529            self::TYPE_PAREN_CLOSE => [
1530                self::ACTION_POP => true,
1531            ],
1532        ],
1533
1534        // State after `{ foo:` expecting an expression as the value of a key in an object literal.
1535        //
1536        // Like EXPRESSION, except that a comma (in PROPERTY_EXPRESSION_OP) goes to PROPERTY_ASSIGNMENT instead
1537        self::PROPERTY_EXPRESSION => [
1538            self::TYPE_BRACE_OPEN => [
1539                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1540                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1541            ],
1542            self::TYPE_BRACE_CLOSE => [
1543                self::ACTION_POP => true,
1544            ],
1545            self::TYPE_PAREN_OPEN => [
1546                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1547                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1548            ],
1549            self::TYPE_FUNC => [
1550                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1551                self::ACTION_GOTO => self::FUNC,
1552            ],
1553            self::TYPE_CLASS => [
1554                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1555                self::ACTION_GOTO => self::CLASS_DEF,
1556            ],
1557            self::TYPE_LITERAL => [
1558                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1559            ],
1560            self::TYPE_ASYNC => [
1561                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_ASYNC,
1562            ],
1563            // 'return' can't appear here, but 'yield' can
1564            self::TYPE_RETURN => [
1565                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_NO_NL,
1566            ],
1567        ],
1568        // Like PROPERTY_EXPRESSION, except that semicolon insertion can happen
1569        // See also EXPRESSION_NO_NL
1570        self::PROPERTY_EXPRESSION_NO_NL => [
1571            self::TYPE_BRACE_OPEN => [
1572                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1573                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1574            ],
1575            self::TYPE_BRACE_CLOSE => [
1576                self::ACTION_POP => true,
1577            ],
1578            self::TYPE_PAREN_OPEN => [
1579                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1580                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1581            ],
1582            self::TYPE_FUNC => [
1583                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1584                self::ACTION_GOTO => self::FUNC,
1585            ],
1586            self::TYPE_CLASS => [
1587                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1588                self::ACTION_GOTO => self::CLASS_DEF,
1589            ],
1590            self::TYPE_LITERAL => [
1591                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1592            ],
1593            // 'yield' can appear here, because 'yield yield' is allowed
1594            self::TYPE_RETURN => [
1595                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_NO_NL,
1596            ],
1597            self::TYPE_UN_OP => [
1598                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1599            ],
1600            self::TYPE_INCR_OP => [
1601                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1602            ],
1603            // BIN_OP seems impossible at the start of an expression, but it can happen in
1604            // yield *foo
1605            self::TYPE_BIN_OP => [
1606                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1607            ],
1608            self::TYPE_ADD_OP => [
1609                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1610            ],
1611        ],
1612
1613        // State after `{ foo: bar`
1614        //
1615        // Like EXPRESSION_OP, but in a property expression, see PROPERTY_EXPRESSION
1616        self::PROPERTY_EXPRESSION_OP => [
1617            self::TYPE_BIN_OP => [
1618                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1619            ],
1620            self::TYPE_ADD_OP => [
1621                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1622            ],
1623            self::TYPE_DOT => [
1624                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_DOT,
1625            ],
1626            self::TYPE_HOOK => [
1627                self::ACTION_PUSH => self::PROPERTY_EXPRESSION,
1628                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1629            ],
1630            self::TYPE_COMMA => [
1631                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1632            ],
1633            self::TYPE_ARROW => [
1634                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_ARROWFUNC,
1635            ],
1636            self::TYPE_BRACE_OPEN => [
1637                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1638            ],
1639            self::TYPE_BRACE_CLOSE => [
1640                self::ACTION_POP => true,
1641            ],
1642            self::TYPE_PAREN_OPEN => [
1643                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1644                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1645            ],
1646        ],
1647
1648        // State after `{ foo: async`
1649        //
1650        // Like PROPERTY_EXPRESSION_OP, but with an added TYPE_FUNC handler.
1651        //
1652        // This state exists to support "{ foo: async function() {",
1653        // which can't re-use PROPERTY_EXPRESSION_OP, because handling TYPE_FUNC there
1654        // would treat invalid "{ foo: bar function () {" as valid.
1655        //
1656        // For other cases we treat "async" like a literal key or key-less value.
1657        //
1658        // ```
1659        // var noAsyncHere = {
1660        //   async,
1661        //   async: 1,
1662        //   async() { return 2; },
1663        //   foo: async
1664        //   foo: async + 2,
1665        //   foo: async(),
1666        // }
1667        // ```
1668        self::PROPERTY_EXPRESSION_ASYNC => [
1669            self::TYPE_BIN_OP => [
1670                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1671            ],
1672            self::TYPE_ADD_OP => [
1673                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1674            ],
1675            self::TYPE_DOT => [
1676                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_DOT,
1677            ],
1678            self::TYPE_HOOK => [
1679                self::ACTION_PUSH => self::PROPERTY_EXPRESSION,
1680                self::ACTION_GOTO => self::EXPRESSION_TERNARY,
1681            ],
1682            self::TYPE_COMMA => [
1683                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1684            ],
1685            self::TYPE_ARROW => [
1686                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_ARROWFUNC,
1687            ],
1688            self::TYPE_BRACE_OPEN => [
1689                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1690            ],
1691            self::TYPE_BRACE_CLOSE => [
1692                self::ACTION_POP => true,
1693            ],
1694            self::TYPE_PAREN_OPEN => [
1695                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1696                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1697            ],
1698            self::TYPE_FUNC => [
1699                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1700                self::ACTION_GOTO => self::FUNC,
1701            ],
1702        ],
1703
1704        // State after `{ foo: bar.`
1705        //
1706        // Like EXPRESSION_DOT, but in a property expression, see PROPERTY_EXPRESSION
1707        self::PROPERTY_EXPRESSION_DOT => [
1708            self::TYPE_LITERAL => [
1709                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1710            ],
1711            // The following are keywords behaving as literals
1712            self::TYPE_ASYNC => [
1713                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1714            ],
1715            self::TYPE_RETURN => [
1716                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1717            ],
1718            self::TYPE_IF => [
1719                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1720            ],
1721            self::TYPE_DO => [
1722                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1723            ],
1724            self::TYPE_VAR => [
1725                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1726            ],
1727            self::TYPE_FUNC => [
1728                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1729            ],
1730            self::TYPE_CLASS => [
1731                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1732            ],
1733            // We don't expect real unary/binary operators here, but some keywords
1734            // (new, delete, void, typeof, instanceof, in) are classified as such, and they can be
1735            // used as property names
1736            self::TYPE_UN_OP => [
1737                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1738            ],
1739            self::TYPE_BIN_OP => [
1740                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1741            ],
1742            self::TYPE_PAREN_OPEN => [
1743                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1744                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1745            ],
1746        ],
1747        // Like EXPRESSION_ARROWFUNC, but in a property expression, see PROPERTY_EXPRESSION
1748        self::PROPERTY_EXPRESSION_ARROWFUNC => [
1749            self::TYPE_UN_OP => [
1750                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1751            ],
1752            self::TYPE_INCR_OP => [
1753                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1754            ],
1755            self::TYPE_ADD_OP => [
1756                self::ACTION_GOTO => self::PROPERTY_EXPRESSION,
1757            ],
1758            self::TYPE_BRACE_OPEN => [
1759                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1760                self::ACTION_GOTO => self::STATEMENT,
1761            ],
1762            self::TYPE_PAREN_OPEN => [
1763                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1764                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1765            ],
1766            self::TYPE_FUNC => [
1767                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1768                self::ACTION_GOTO => self::FUNC,
1769            ],
1770            self::TYPE_CLASS => [
1771                self::ACTION_PUSH => self::PROPERTY_EXPRESSION_OP,
1772                self::ACTION_GOTO => self::CLASS_DEF,
1773            ],
1774            self::TYPE_LITERAL => [
1775                self::ACTION_GOTO => self::PROPERTY_EXPRESSION_OP,
1776            ],
1777        ],
1778        // Class definition (after the class keyword). Expects a BindingIdentifier
1779        // and/or ClassHeritage, followed by {, which starts a class body. The class
1780        // body's closing } will pop the stack, so the state to return to after the
1781        // class definition should be pushed to the stack first.
1782        self::CLASS_DEF => [
1783            self::TYPE_BRACE_OPEN => [
1784                self::ACTION_GOTO => self::PROPERTY_ASSIGNMENT,
1785            ],
1786            self::TYPE_PAREN_OPEN => [
1787                self::ACTION_PUSH => self::CLASS_DEF,
1788                self::ACTION_GOTO => self::PAREN_EXPRESSION,
1789            ],
1790            self::TYPE_FUNC => [
1791                self::ACTION_PUSH => self::CLASS_DEF,
1792                self::ACTION_GOTO => self::FUNC,
1793            ],
1794        ],
1795        // Import or export declaration
1796        self::IMPORT_EXPORT => [
1797            self::TYPE_SEMICOLON => [
1798                self::ACTION_GOTO => self::STATEMENT,
1799            ],
1800            self::TYPE_VAR => [
1801                self::ACTION_GOTO => self::EXPRESSION,
1802            ],
1803            self::TYPE_FUNC => [
1804                self::ACTION_PUSH => self::EXPRESSION_OP,
1805                self::ACTION_GOTO => self::FUNC,
1806            ],
1807            self::TYPE_CLASS => [
1808                self::ACTION_PUSH => self::EXPRESSION_OP,
1809                self::ACTION_GOTO => self::CLASS_DEF,
1810            ],
1811            self::TYPE_SPECIAL => [
1812                'default' => [
1813                    self::ACTION_GOTO => self::EXPRESSION,
1814                ],
1815                // Stay in this state for *, as, from
1816                '*' => [],
1817                'as' => [],
1818                'from' => [],
1819            ],
1820        ],
1821        // Used in template string-specific code below
1822        self::TEMPLATE_STRING_HEAD => [
1823            self::TYPE_LITERAL => [
1824                self::ACTION_PUSH => self::TEMPLATE_STRING_TAIL,
1825                self::ACTION_GOTO => self::EXPRESSION,
1826            ],
1827        ],
1828    ];
1829
1830    /**
1831     * @var array $semicolon
1832     *
1833     * Rules for when semicolon insertion is appropriate. Semicolon insertion happens if we are
1834     * in one of these states, and encounter one of these tokens preceded by a newline.
1835     *
1836     * This array is augmented by ensureExpandedStates().
1837     */
1838    private static $semicolon = [
1839        self::EXPRESSION_NO_NL => [
1840            self::TYPE_UN_OP => true,
1841            // BIN_OP seems impossible at the start of an expression, but it can happen in
1842            // yield *foo
1843            self::TYPE_BIN_OP => true,
1844            self::TYPE_INCR_OP => true,
1845            self::TYPE_ADD_OP => true,
1846            self::TYPE_BRACE_OPEN => true,
1847            self::TYPE_PAREN_OPEN => true,
1848            self::TYPE_RETURN => true,
1849            self::TYPE_IF => true,
1850            self::TYPE_DO => true,
1851            self::TYPE_VAR => true,
1852            self::TYPE_FUNC => true,
1853            self::TYPE_CLASS => true,
1854            self::TYPE_LITERAL => true,
1855            self::TYPE_ASYNC => true,
1856        ],
1857        self::EXPRESSION_TERNARY_NO_NL => [
1858            self::TYPE_UN_OP => true,
1859            // BIN_OP seems impossible at the start of an expression, but it can happen in
1860            // yield *foo
1861            self::TYPE_BIN_OP => true,
1862            self::TYPE_INCR_OP => true,
1863            self::TYPE_ADD_OP => true,
1864            self::TYPE_BRACE_OPEN => true,
1865            self::TYPE_PAREN_OPEN => true,
1866            self::TYPE_RETURN => true,
1867            self::TYPE_IF => true,
1868            self::TYPE_DO => true,
1869            self::TYPE_VAR => true,
1870            self::TYPE_FUNC => true,
1871            self::TYPE_CLASS => true,
1872            self::TYPE_LITERAL => true,
1873            self::TYPE_ASYNC => true,
1874        ],
1875        self::PAREN_EXPRESSION_NO_NL => [
1876            self::TYPE_UN_OP => true,
1877            // BIN_OP seems impossible at the start of an expression, but it can happen in
1878            // yield *foo
1879            self::TYPE_BIN_OP => true,
1880            self::TYPE_INCR_OP => true,
1881            self::TYPE_ADD_OP => true,
1882            self::TYPE_BRACE_OPEN => true,
1883            self::TYPE_PAREN_OPEN => true,
1884            self::TYPE_RETURN => true,
1885            self::TYPE_IF => true,
1886            self::TYPE_DO => true,
1887            self::TYPE_VAR => true,
1888            self::TYPE_FUNC => true,
1889            self::TYPE_CLASS => true,
1890            self::TYPE_LITERAL => true,
1891            self::TYPE_ASYNC => true,
1892        ],
1893        self::PROPERTY_EXPRESSION_NO_NL => [
1894            self::TYPE_UN_OP => true,
1895            // BIN_OP seems impossible at the start of an expression, but it can happen in
1896            // yield *foo
1897            self::TYPE_BIN_OP => true,
1898            self::TYPE_INCR_OP => true,
1899            self::TYPE_ADD_OP => true,
1900            self::TYPE_BRACE_OPEN => true,
1901            self::TYPE_PAREN_OPEN => true,
1902            self::TYPE_RETURN => true,
1903            self::TYPE_IF => true,
1904            self::TYPE_DO => true,
1905            self::TYPE_VAR => true,
1906            self::TYPE_FUNC => true,
1907            self::TYPE_CLASS => true,
1908            self::TYPE_LITERAL => true,
1909            self::TYPE_ASYNC => true,
1910        ],
1911        self::EXPRESSION_OP => [
1912            self::TYPE_UN_OP => true,
1913            self::TYPE_INCR_OP => true,
1914            self::TYPE_BRACE_OPEN => true,
1915            self::TYPE_RETURN => true,
1916            self::TYPE_IF => true,
1917            self::TYPE_DO => true,
1918            self::TYPE_VAR => true,
1919            self::TYPE_FUNC => true,
1920            self::TYPE_CLASS => true,
1921            self::TYPE_LITERAL => true,
1922            self::TYPE_ASYNC => true,
1923        ],
1924        self::EXPRESSION_END => [
1925            self::TYPE_UN_OP => true,
1926            self::TYPE_INCR_OP => true,
1927            self::TYPE_ADD_OP => true,
1928            self::TYPE_BRACE_OPEN => true,
1929            self::TYPE_PAREN_OPEN => true,
1930            self::TYPE_RETURN => true,
1931            self::TYPE_IF => true,
1932            self::TYPE_DO => true,
1933            self::TYPE_VAR => true,
1934            self::TYPE_FUNC => true,
1935            self::TYPE_CLASS => true,
1936            self::TYPE_LITERAL => true,
1937            self::TYPE_ASYNC => true,
1938        ],
1939        self::PAREN_EXPRESSION_OP_NO_NL => [
1940            self::TYPE_FUNC => true,
1941        ]
1942    ];
1943
1944    /**
1945     * @var array $divStates
1946     *
1947     * States in which a / is a division operator. In all other states, it's the start of a regex.
1948     *
1949     * This array is augmented by self::ensureExpandedStates().
1950     */
1951    private static $divStates = [
1952        self::EXPRESSION_OP             => true,
1953        self::EXPRESSION_TERNARY_OP     => true,
1954        self::PAREN_EXPRESSION_OP       => true,
1955        self::PROPERTY_EXPRESSION_OP    => true,
1956        self::PROPERTY_EXPRESSION_ASYNC => true
1957    ];
1958
1959    /**
1960     * Add copies of all states but with negative numbers to self::$model (if not already present),
1961     * to represent generator function states.
1962     */
1963    private static function ensureExpandedStates() {
1964        // Already done?
1965        if ( self::$expandedStates ) {
1966            return;
1967        }
1968        self::$expandedStates = true;
1969
1970        // Add copies of all states (except FUNC and GENFUNC) with negative numbers.
1971        // These negative states represent states inside generator functions. When in these states,
1972        // TYPE_YIELD is treated as TYPE_RETURN, otherwise as TYPE_LITERAL
1973        foreach ( self::$model as $state => $transitions ) {
1974            if ( $state === self::FUNC || $state === self::GENFUNC ) {
1975                continue;
1976            }
1977            foreach ( $transitions as $tokenType => $actions ) {
1978                foreach ( $actions as $action => $target ) {
1979                    if ( !is_array( $target ) ) {
1980                        self::$model[-$state][$tokenType][$action] = (
1981                            $target === self::FUNC ||
1982                            $target === true ||
1983                            $target === self::GENFUNC
1984                        ) ? $target : -$target;
1985                        continue;
1986                    }
1987
1988                    foreach ( $target as $subaction => $subtarget ) {
1989                        self::$model[-$state][$tokenType][$action][$subaction] = (
1990                            $subtarget === self::FUNC ||
1991                            $subtarget === true ||
1992                            $subtarget === self::GENFUNC
1993                        ) ? $subtarget : -$subtarget;
1994                    }
1995                }
1996            }
1997        }
1998        // Special cases:
1999        // '{' in a property assignment starts a method, so it shouldn't be flipped
2000        self::$model[-self::PROPERTY_ASSIGNMENT][self::TYPE_BRACE_OPEN][self::ACTION_GOTO] = self::STATEMENT;
2001
2002        // Also add negative versions of states to the other arrays
2003        foreach ( self::$semicolon as $state => $value ) {
2004            self::$semicolon[-$state] = $value;
2005        }
2006        foreach ( self::$divStates as $state => $value ) {
2007            self::$divStates[-$state] = $value;
2008        }
2009    }
2010
2011    /**
2012     * Returns minified JavaScript code.
2013     *
2014     * @see MinifierState::setErrorHandler
2015     * @param string $s JavaScript code to minify
2016     * @param callable|null $onError Called with a ParseError object
2017     * @return string Minified code
2018     */
2019    public static function minify( $s, $onError = null ) {
2020        return self::minifyInternal( $s, null, $onError );
2021    }
2022
2023    /**
2024     * Create a minifier state object without source map capabilities
2025     *
2026     * Example:
2027     *
2028     *   JavaScriptMinifier::createMinifier()
2029     *     ->addSourceFile( 'file.js', $source )
2030     *     ->getMinifiedOutput();
2031     *
2032     * @return JavaScriptMinifierState
2033     */
2034    public static function createMinifier() {
2035        return new JavaScriptMinifierState;
2036    }
2037
2038    /**
2039     * Create a minifier state object with source map capabilities
2040     *
2041     * Example:
2042     *
2043     *   $mapper = JavaScriptMinifier::createSourceMapState()
2044     *     ->addSourceFile( 'file1.js', $source1 )
2045     *     ->addOutput( "\n\n" )
2046     *     ->addSourceFile( 'file2.js', $source2 );
2047     *   $out = $mapper->getMinifiedOutput();
2048     *   $map = $mapper->getSourceMap()
2049     *
2050     * @return JavaScriptMapperState
2051     */
2052    public static function createSourceMapState() {
2053        return new JavaScriptMapperState;
2054    }
2055
2056    /**
2057     * Create a MinifierState that doesn't actually minify
2058     *
2059     * @return IdentityMinifierState
2060     */
2061    public static function createIdentityMinifier() {
2062        return new IdentityMinifierState;
2063    }
2064
2065    private static function getNextNonWhitespaceChar( string $s, int $pos ): ?string {
2066        $length = strlen( $s );
2067        // This is an exact copy of the whitespace/comment recognition in minifyInternal().
2068        // Keep the scanner logic in sync with the inlined version there.
2069        while ( $pos < $length ) {
2070            $skip = strspn( $s, " \t\n\r\xb\xc", $pos );
2071            if ( $skip ) {
2072                $pos += $skip;
2073                continue;
2074            }
2075            if ( substr( $s, $pos, 2 ) === '/*' ) {
2076                $end = strpos( $s, '*/', $pos + 2 );
2077                if ( $end === false ) {
2078                    return null;
2079                }
2080                $pos = $end + 2;
2081                continue;
2082            }
2083            if (
2084                substr( $s, $pos, 2 ) === '//' ||
2085                substr( $s, $pos, 4 ) === '<!--' ||
2086                substr( $s, $pos, 3 ) === '-->'
2087            ) {
2088                $skip = strcspn( $s, "\r\n", $pos );
2089                $pos += $skip;
2090                continue;
2091            }
2092            return $s[$pos];
2093        }
2094        return null;
2095    }
2096
2097    /**
2098     * Minify with optional source map.
2099     *
2100     * @internal
2101     *
2102     * @param string $s
2103     * @param MappingsGenerator|null $mapGenerator
2104     * @param callable|null $onError
2105     * @param callable|null $onDebug See augmentDebugContext() for callback parameter
2106     * @return string
2107     */
2108    public static function minifyInternal( $s, $mapGenerator = null, $onError = null, $onDebug = null ) {
2109        self::ensureExpandedStates();
2110
2111        // Optimization: alias static properties accessed in the hot loop to local variables.
2112        $opChars = self::$opChars;
2113        $multicharPuncTokens = self::MULTICHAR_PUNCTOKENS;
2114        $tokenTypes = self::$tokenTypes;
2115        $model = self::$model;
2116        $semicolon = self::$semicolon;
2117        $divStates = self::$divStates;
2118        $maxLineLength = self::$maxLineLength;
2119
2120        // Here's where the minifying takes place: Loop through the input, looking for tokens
2121        // and output them to $out, taking actions to the above defined rules when appropriate.
2122        $error = null;
2123        $out = '';
2124        $pos = 0;
2125        $length = strlen( $s );
2126        $lineLength = 0;
2127        $plainDigits = false;
2128        $lastPlainDigits = false;
2129        $newlineFound = true;
2130        $state = self::STATEMENT;
2131        $stack = [];
2132        // Optimization: calling end( $stack ) repeatedly is expensive
2133        $topOfStack = null;
2134        // Pretend that we have seen a semicolon yet
2135        $last = ';';
2136
2137        // Handle initial hashbang comment
2138        if ( str_starts_with( $s, '#!' ) ) {
2139            $skip = strcspn( $s, "\r\n" );
2140            $token = substr( $s, 0, $skip );
2141            $lineBreakLength = 0;
2142            if ( $skip < $length ) {
2143                $lineBreakLength = (
2144                    $s[$skip] === "\r" && $skip + 1 < $length && $s[$skip + 1] === "\n"
2145                ) ? 2 : 1;
2146            }
2147            if ( $mapGenerator ) {
2148                $mapGenerator->outputToken( $token );
2149                if ( $lineBreakLength ) {
2150                    $mapGenerator->outputSpace( "\n" );
2151                }
2152                $mapGenerator->consumeSource( $skip + $lineBreakLength );
2153            }
2154            $out .= $token;
2155            if ( $lineBreakLength ) {
2156                $out .= "\n";
2157            } else {
2158                $lineLength = strlen( $token );
2159                $newlineFound = false;
2160            }
2161            $pos = $skip + $lineBreakLength;
2162        }
2163
2164        while ( $pos < $length ) {
2165            // First, skip over any whitespace and line breaks
2166            //
2167            // ECMAScript 2025 Â§ 12.2 White Space
2168            // https://262.ecma-international.org/16.0/#sec-white-space
2169            //
2170            // - U+0009 Tab (\t)
2171            // - U+000B Line Tabulation (VT, \v in JavaScript, \xb binary in PHP)
2172            // - U+000C Form Feed (FF, \f in JavaScript, \xc binary in PHP)
2173            // - U+0020 Space
2174            // - [Not implemented] U+00A0 No Break Space (NBSP)
2175            // - [Not implemented] U+FEFF Zero Width No-Break Space (ZWNBSP)
2176            // - [Not implemented] Any other Unicode "Space_Separator (Zs)" code point
2177            //
2178            // ECMAScript 2025 Â§ 12.3 Line Terminators
2179            // - U+000A Line Feed (LF, \n)
2180            // - U+000D Carriage Return (CR, \r)
2181            // - [Not implemented] U+2028 Line Separator (LS)
2182            // - [Not implemented] U+2029 Paragraph Separator (PS)
2183            //
2184            // The U+2028 and U+2029 codepoints are multibyte characters that are extremely unlikely
2185            // to appear in source code because there is no reason for either hand-written or
2186            // machine-generated code to use them as line terminators. ES2019 instead allowed
2187            // them in string literals to make JSON text a syntactic subset of ECMAScript.
2188            // We don't implement them as line terminators because doing so would slow down all
2189            // parsing, especially for "end of inline comment" and "end of identifier or reserved
2190            // word". It is acceptable that we simply don't support such input. In simple cases
2191            // such input would actually work fine, but it may cause invalid output.
2192            //
2193            // NOTE: We do support multibyte line terminators in multi-line string literals and
2194            // template string literals.
2195            //
2196            // Optimization: Rearrange with Space, Tab, and Line Feed first which are most common.
2197            //
2198            // Optimization: We inline getNextNonWhitespaceChar() here because it is a hot path.
2199            //
2200            // NOTE: Keep the scanner logic in sync with getNextNonWhitespaceChar().
2201            $skip = strspn( $s, " \t\n\r\xb\xc", $pos );
2202            if ( !$skip ) {
2203                $ch = $s[$pos];
2204
2205                // Skip multiline comment. Search for the end token or EOT.
2206                if ( $ch === '/' && substr( $s, $pos, 2 ) === '/*' ) {
2207                    $end = strpos( $s, '*/', $pos + 2 );
2208                    $skip = $end === false ? $length - $pos : $end - $pos + 2;
2209                }
2210            }
2211
2212            // Record whether we skipped over a newline in whitespace or multiline comment.
2213            // The semicolon insertion mechanism must know whether there was a newline between tokens.
2214            if ( $skip ) {
2215                if ( !$newlineFound && strcspn( $s, "\r\n", $pos, $skip ) !== $skip ) {
2216                    $newlineFound = true;
2217                }
2218                if ( $mapGenerator ) {
2219                    $mapGenerator->consumeSource( $skip );
2220                }
2221                $pos += $skip;
2222                continue;
2223            }
2224            // Handle C++-style comments and html comments, which are treated as single line
2225            // comments by the browser, regardless of whether the end tag is on the same line.
2226            // Handle --> the same way, but only if it's at the beginning of the line
2227            // @phan-suppress-next-line PhanPossiblyUndeclaredVariable
2228            if ( ( $ch === '/' && substr( $s, $pos, 2 ) === '//' )
2229                || ( $ch === '<' && substr( $s, $pos, 4 ) === '<!--' )
2230                || ( $ch === '-' && $newlineFound && substr( $s, $pos, 3 ) === '-->' )
2231            ) {
2232                $skip = strcspn( $s, "\r\n", $pos );
2233                if ( $mapGenerator ) {
2234                    $mapGenerator->consumeSource( $skip );
2235                }
2236                $pos += $skip;
2237                continue;
2238            }
2239
2240            // Find out which kind of token we're handling.
2241            // Note: $end must point past the end of the current token
2242            // so that `substr($s, $pos, $end - $pos)` would be the entire token.
2243            // In order words, $end will be the offset of the last relevant character
2244            // in the stream + 1, or simply put: The offset of the first character
2245            // of any next token in the stream.
2246            $end = $pos + 1;
2247            // Handle string literals
2248            if ( $ch === "'" || $ch === '"' ) {
2249                // Search to the end of the string literal, skipping over backslash escapes
2250                $search = $ch . '\\';
2251                do {
2252                    // Speculatively add 2 to the end so that if we see a backslash,
2253                    // the next iteration will start 2 characters further (one for the
2254                    // backslash, one for the escaped character).
2255                    // We'll correct this outside the loop.
2256                    $end += strcspn( $s, $search, $end ) + 2;
2257                    // If the last character in our search for a quote or a backlash
2258                    // matched a backslash and we haven't reached the end, keep searching..
2259                } while ( $end - 2 < $length && $s[$end - 2] === '\\' );
2260                // Correction (1): Undo speculative add, keep only one (end of string literal)
2261                $end--;
2262                if ( $end > $length ) {
2263                    // Correction (2): Loop wrongly assumed an end quote ended the search,
2264                    // but search ended because we've reached the end. Correct $end.
2265                    // TODO: This is invalid and should throw.
2266                    $end--;
2267                }
2268
2269            // Handle template strings, either from "`" to begin a new string,
2270            // or continuation after the "}" that ends a "${"-expression.
2271            } elseif ( $ch === '`' || ( $ch === '}' && $topOfStack === self::TEMPLATE_STRING_TAIL ) ) {
2272                if ( $ch === '}' ) {
2273                    // Pop the TEMPLATE_STRING_TAIL state off the stack
2274                    // We don't let it get popped off the stack the normal way, to avoid the newline
2275                    // and comment stripping code above running on the continuation of the literal
2276                    array_pop( $stack );
2277                    // Also pop the previous state off the stack
2278                    $state = array_pop( $stack );
2279                    $topOfStack = end( $stack );
2280                }
2281                // Search until we reach either a closing ` or a ${, skipping over backslash escapes
2282                // and $ characters followed by something other than { or `
2283                do {
2284                    $end += strcspn( $s, '`$\\', $end ) + 1;
2285                    if ( $end - 1 < $length && $s[$end - 1] === '`' ) {
2286                        // End of the string, stop
2287                        // We don't do this in the while() condition because the $end++ in the
2288                        // backslash escape branch makes it difficult to do so without incorrectly
2289                        // considering an escaped backtick (\`) the end of the string
2290                        break;
2291                    }
2292                    if ( $end - 1 < $length && $s[$end - 1] === '\\' ) {
2293                        // Backslash escape. Skip the next character, and keep going
2294                        $end++;
2295                        continue;
2296                    }
2297                    if ( $end < $length && $s[$end - 1] === '$' && $s[$end] === '{' ) {
2298                        // Beginning of an expression in ${ ... }. Skip the {, and stop
2299                        $end++;
2300                        // Push the current state to the stack. We'll pop this off later when hitting
2301                        // the end of this template string
2302                        $stack[] = $state;
2303                        $topOfStack = $state;
2304                        // Change the state to TEMPLATE_STRING_HEAD. The token type will be detected
2305                        // as TYPE_LITERAL, and this will cause the state machine to expect an
2306                        // expression, then go to the TEMPLATE_STRING_TAIL state when it hits the }
2307                        $state = self::TEMPLATE_STRING_HEAD;
2308                        break;
2309                    }
2310                } while ( $end - 1 < $length );
2311                if ( $end > $length ) {
2312                    // Loop wrongly assumed an end quote or ${ ended the search,
2313                    // but search ended because we've reached the end. Correct $end.
2314                    // TODO: This is invalid and should throw.
2315                    $end--;
2316                }
2317
2318            // We have to distinguish between regexp literals and division operators
2319            // A division operator is only possible in certain states
2320            } elseif ( $ch === '/' && !isset( $divStates[$state] ) ) {
2321                // Regexp literal
2322                for ( ; ; ) {
2323                    // Search until we find "/" (end of regexp), "\" (backslash escapes),
2324                    // or "[" (start of character classes).
2325                    do {
2326                        // Speculatively add 2 to ensure next iteration skips
2327                        // over backslash and escaped character.
2328                        // We'll correct this outside the loop.
2329                        $end += strcspn( $s, '/[\\', $end ) + 2;
2330                        // If backslash escape, keep searching...
2331                    } while ( $end - 2 < $length && $s[$end - 2] === '\\' );
2332                    // Correction (1): Undo speculative add, keep only one (end of regexp)
2333                    $end--;
2334                    if ( $end > $length ) {
2335                        // Correction (2): Loop wrongly assumed end slash was seen
2336                        // String ended without end of regexp. Correct $end.
2337                        // TODO: This is invalid and should throw.
2338                        $end--;
2339                        break;
2340                    }
2341                    if ( $s[$end - 1] === '/' ) {
2342                        break;
2343                    }
2344                    // (Implicit else), we must've found the start of a char class,
2345                    // skip until we find "]" (end of char class), or "\" (backslash escape)
2346                    do {
2347                        // Speculatively add 2 for backslash escape.
2348                        // We'll substract one outside the loop.
2349                        $end += strcspn( $s, ']\\', $end ) + 2;
2350                        // If backslash escape, keep searching...
2351                    } while ( $end - 2 < $length && $s[$end - 2] === '\\' );
2352                    // Correction (1): Undo speculative add, keep only one (end of regexp)
2353                    $end--;
2354                    if ( $end > $length ) {
2355                        // Correction (2): Loop wrongly assumed "]" was seen
2356                        // String ended without ending char class or regexp. Correct $end.
2357                        // TODO: This is invalid and should throw.
2358                        $end--;
2359                        break;
2360                    }
2361                }
2362                // Search past the regexp modifiers (gi)
2363                while ( $end < $length && ctype_alpha( $s[$end] ) ) {
2364                    $end++;
2365                }
2366
2367            // @phan-suppress-next-line PhanParamSuspiciousOrder
2368            } elseif ( $ch === '0' && $pos + 1 < $length && str_contains( 'xXbBoO', $s[$pos + 1] ) ) {
2369                // Non-decimal integer literal, with optional BigInt suffix.
2370                $end++;
2371                $prefix = $s[$pos + 1];
2372                $digits = match ( $prefix ) {
2373                    'x', 'X' => '0123456789ABCDEFabcdef',
2374                    'b', 'B' => '01',
2375                    'o', 'O' => '01234567',
2376                };
2377                $len = strspn( $s, $digits . '_', $end );
2378                if ( !$len && !$error ) {
2379                    $base = match ( $prefix ) {
2380                        'x', 'X' => 'hexadecimal',
2381                        'b', 'B' => 'binary',
2382                        'o', 'O' => 'octal',
2383                    };
2384                    $error = new ParseError(
2385                        "Expected a $base number but found " . substr( $s, $pos, 5 ),
2386                        $pos,
2387                    );
2388                }
2389                $end += $len;
2390                if ( $end < $length && $s[$end] === 'n' ) {
2391                    $end++;
2392                }
2393            } elseif (
2394                // Optimisation: This check must accept only ASCII digits 0-9.
2395                // Avoid ctype_digit() because it is slower and also accepts locale-specific digits.
2396                // Using is_numeric() might seem wrong also as it accepts negative numbers, decimal
2397                // numbers, and exponents (e.g. strings like "+012.34e6"). But, it is fine here
2398                // because we know $ch is a single character, and we believe the only single
2399                // characters that is_numeric() accepts are ASCII digits 0-9.
2400                is_numeric( $ch )
2401                || ( $ch === '.' && $pos + 1 < $length && is_numeric( $s[$pos + 1] ) )
2402            ) {
2403                $end += strspn( $s, '0123456789_', $end );
2404                if ( $ch === '.' ) {
2405                    // Valid: ".42" (number literal, fraction with implied zero)
2406                    // Valid: ".42_000"
2407                    $decimal = 1;
2408                } else {
2409                    $decimal = strspn( $s, '.', $end );
2410                    if ( $decimal ) {
2411                        // Valid: "5." (number literal, optional fraction)
2412                        // Valid: "5_0." (number literal, optional fraction)
2413                        // Valid: "5.42" (number literal)
2414                        // Valid: "5..toString" (number literal "5.", followed by member expression)
2415                        // Valid: "5..a_100"    (number literal "5.", followed by member expression)
2416                        // Valid: "5. .a_100"   (number literal "5.", followed by member expression)
2417                        // Valid: "5_0.4_2.toString" (number "50.42", followed by member expression)
2418                        // Invalid: "5..42"
2419                        // Invalid: "5...42"
2420                        // Invalid: "5...toString"
2421                        // Invalid: "5._.toString" (numeric separator must be between digits, undetected)
2422                        // Invalid: "5_.toString" (numeric separator not allowed at end of number, undetected)
2423                        $fraction = strspn( $s, '0123456789_', $end + $decimal );
2424                        if ( $decimal === 2 && !$fraction ) {
2425                            // Rewind one character, so that the member expression dot
2426                            // will be parsed as the next token (TYPE_DOT).
2427                            $decimal = 1;
2428                        }
2429                        if ( $decimal > 1 && !$error ) {
2430                            $error = new ParseError( 'Too many decimal points', $end );
2431                        }
2432                        $end += $decimal + $fraction;
2433                    } else {
2434                        // Valid: "42"
2435                        // Valid: "42_000"
2436                        // Invalid: "5_" (numeric separator not allowed at end of number, undetected)
2437                        $plainDigits = true;
2438                    }
2439                }
2440                $exponent = strspn( $s, 'eE', $end );
2441                if ( $exponent ) {
2442                    if ( $exponent > 1 && !$error ) {
2443                        $error = new ParseError( 'Number with several E', $end );
2444                    }
2445                    $end += $exponent;
2446
2447                    // + sign is optional; - sign is required.
2448                    $end += strspn( $s, '-+', $end );
2449                    $len = strspn( $s, '0123456789_', $end );
2450                    if ( !$len && !$error ) {
2451                        $error = new ParseError(
2452                            'Missing decimal digits after exponent',
2453                            $pos
2454                        );
2455                    }
2456                    $end += $len;
2457                    $plainDigits = false;
2458                }
2459                if ( !$decimal && !$exponent && $end < $length && $s[$end] === 'n' ) {
2460                    $end++;
2461                    $plainDigits = false;
2462                }
2463            } elseif ( isset( $multicharPuncTokens[$ch] ) ) {
2464                // Optimization: Parse multi-character punctuation operators with direct lookahead
2465                // <https://gerrit.wikimedia.org/r/c/mediawiki/libs/Minify/+/1221106>
2466                if (
2467                    $pos + 1 < $length &&
2468                    // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found
2469                    ( $submap2 = $multicharPuncTokens[$ch][$s[$pos + 1]] ?? null )
2470                ) {
2471                    if (
2472                        $ch === '?' &&
2473                        $s[$pos + 1] === '.' &&
2474                        $pos + 2 < $length &&
2475                        is_numeric( $s[$pos + 2] )
2476                    ) {
2477                        // ECMAScript 2025 Â§ 12.8 Punctuators
2478                        // OptionalChainingPunctuator is not recognised before a decimal digit.
2479                    } elseif ( $submap2 === 2 ) {
2480                        // Optimization: Shortcut for the common case of an unambiguous 2-char punctuation token
2481                        $end = $pos + 2;
2482                    } else {
2483                        $next3 = $pos + 2 < $length ? $s[$pos + 2] : '';
2484                        $next4 = $pos + 3 < $length ? $s[$pos + 3] : '';
2485                        // 4-char token,
2486                        // or 3-char token,
2487                        // or 2-char token that is a subset of a not-seen 3- or 4-char token
2488                        //
2489                        // NOTE: The `1` fallback ensures graceful handling of invalid syntax like `..*`,
2490                        // instead of causing infinite recursion. We don't need to set `$pos + 1`, because
2491                        // that is the default, but we assign unconditionally here because all valid syntax
2492                        // needs an assignment. Adding checks to avoid it for invalid syntax doesn't pay off.
2493                        $end = $pos + ( $submap2[$next3][$next4] ?? $submap2[$next3][''] ?? $submap2[''] ?? 1 );
2494                    }
2495                }
2496                // All other opChars ({, }, (, ), [, ], :, ;, ,, ~, etc) are single-char tokens
2497                // so $end (which is $pos + 1) is already correct.
2498            } elseif ( !isset( $opChars[$ch] ) ) {
2499                // Identifier or reserved word. Search for the end by excluding whitespace and
2500                // punctuation.
2501                $end += strcspn( $s, " \t\n.;,=<>+-{}()[]?:*/%'\"`!&|^~\xb\xc\r", $end );
2502            }
2503
2504            // Now get the token type from our type array
2505            // so $end - $pos == strlen( $token )
2506            $token = substr( $s, $pos, $end - $pos );
2507            $isImportExpression = (
2508                $token === 'import' &&
2509                abs( $state ) === self::STATEMENT &&
2510                in_array( self::getNextNonWhitespaceChar( $s, $end ), [ '(', '.' ], true )
2511            );
2512            $type = !$isImportExpression && isset( $model[$state][self::TYPE_SPECIAL][$token] )
2513                ? self::TYPE_SPECIAL
2514                : $tokenTypes[$token] ?? self::TYPE_LITERAL;
2515            if ( $type === self::TYPE_YIELD ) {
2516                // yield is treated as TYPE_RETURN inside a generator function (negative state)
2517                // but as TYPE_LITERAL when not in a generator function (positive state)
2518                $type = $state < 0 ? self::TYPE_RETURN : self::TYPE_LITERAL;
2519            }
2520
2521            $pad = '';
2522
2523            if ( $newlineFound && isset( $semicolon[$state][$type] ) ) {
2524                // This token triggers the semicolon insertion mechanism of javascript. While we
2525                // could add the ; token here ourselves, keeping the newline has a few advantages.
2526                $pad = "\n";
2527                $state = $state < 0 ? -self::STATEMENT : self::STATEMENT;
2528                $lineLength = 0;
2529            // This check adds a new line if we have exceeded the max length and only does this if
2530            // a newline was found in this this position, if it wasn't, it uses the next available
2531            // line break
2532            } elseif ( $newlineFound &&
2533                $lineLength + $end - $pos > $maxLineLength &&
2534                !isset( $semicolon[$state][$type] ) &&
2535                $type !== self::TYPE_INCR_OP &&
2536                $type !== self::TYPE_ARROW
2537            ) {
2538                $pad = "\n";
2539                $lineLength = 0;
2540            // Class fields can omit semicolons, so need to preserve newlines after them.
2541            // Preserve all line breaks before non-punctuation tokens in class bodies.
2542            } elseif ( $newlineFound &&
2543                $state === self::PROPERTY_ASSIGNMENT &&
2544                $topOfStack === self::STATEMENT &&
2545                !isset( $opChars[$ch] )
2546            ) {
2547                $pad = "\n";
2548                $lineLength = 0;
2549            // Check, whether we have to separate the token from the last one with whitespace
2550            } elseif ( !isset( $opChars[$last] ) && !isset( $opChars[$ch] ) ) {
2551                $pad = ' ';
2552                $lineLength++;
2553            // Don't accidentally create ++, -- or // tokens
2554            } elseif ( $last === $ch && ( $ch === '+' || $ch === '-' || $ch === '/' ) ) {
2555                $pad = ' ';
2556                $lineLength++;
2557            // Don't create invalid dot notation after number literal (T303827).
2558            // Keep whitespace in "42. foo".
2559            // But keep minifying "foo.bar", "42..foo", and "42.0.foo" per $opChars.
2560            } elseif ( $lastPlainDigits && $type === self::TYPE_DOT && $token !== '?.' ) {
2561                $pad = ' ';
2562                $lineLength++;
2563            }
2564
2565            if ( $onDebug ) {
2566                $onDebug( self::augmentDebugContext( [
2567                    'stack' => $stack,
2568                    'last' => $last,
2569                    'state' => $state,
2570                    'pos' => $pos,
2571                    'ch' => $ch,
2572                    'token' => $token,
2573                    'type' => $type,
2574                ] ) );
2575            }
2576
2577            if ( $mapGenerator ) {
2578                $mapGenerator->outputSpace( $pad );
2579                $mapGenerator->outputToken( $token );
2580                $mapGenerator->consumeSource( $end - $pos );
2581            }
2582            $out .= $pad;
2583            $out .= $token;
2584            $lineLength += $end - $pos;
2585            $last = $s[$end - 1];
2586            $pos = $end;
2587            $newlineFound = false;
2588            $lastPlainDigits = $plainDigits;
2589            $plainDigits = false;
2590
2591            // Now that we have output our token, transition into the new state.
2592            $actions = $type === self::TYPE_SPECIAL ?
2593                $model[$state][$type][$token] :
2594                $model[$state][$type] ?? [];
2595            if ( isset( $actions[self::ACTION_PUSH] ) &&
2596                count( $stack ) < self::STACK_LIMIT
2597            ) {
2598                $topOfStack = $actions[self::ACTION_PUSH];
2599                $stack[] = $topOfStack;
2600            }
2601            if ( $stack && isset( $actions[self::ACTION_POP] ) ) {
2602                $state = array_pop( $stack );
2603                $topOfStack = end( $stack );
2604            } elseif ( isset( $actions[self::ACTION_GOTO] ) ) {
2605                $state = $actions[self::ACTION_GOTO];
2606            }
2607        }
2608        if ( $onError && $error ) {
2609            $onError( $error );
2610        }
2611        return $out;
2612    }
2613
2614    /**
2615     * Replace integer values with the corresponding class constant names
2616     *
2617     * @param array $context
2618     * - int[] 'stack' List of states (class constants)
2619     * - string 'last' Previous character from input stream
2620     * - int 'state' Current state as result of previous character (class constant)
2621     * - int 'pos' Offset of current character in input stream
2622     * - string 'ch' Current character in input stream, first character of current token
2623     * - string 'token' Current token from input stream
2624     * - int 'type' Current type as interpreted from the current character
2625     *
2626     * @return array The $context, with any integer class constants replaced by
2627     * their corresponding class constant name as a string (if found), or else
2628     * their given integer value.
2629     */
2630    private static function augmentDebugContext( array $context ) {
2631        $self = new ReflectionClass( self::class );
2632        foreach ( $self->getConstants() as $name => $value ) {
2633            if ( !is_int( $value ) ) {
2634                continue;
2635            }
2636            foreach ( $context['stack'] as $i => $state ) {
2637                if ( $state === $value ) {
2638                    $context['stack'][$i] = $name;
2639                } elseif ( $state === -$value ) {
2640                    $context['stack'][$i] = '-' . $name;
2641                }
2642            }
2643            if ( $context['state'] === $value ) {
2644                $context['state'] = $name;
2645            } elseif ( $context['state'] === -$value ) {
2646                $context['state'] = '-' . $name;
2647            }
2648            if ( $context['type'] === $value ) {
2649                $context['type'] = $name;
2650            }
2651        }
2652
2653        return $context;
2654    }
2655}