Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php declare(strict_types=1);
2
 
3
namespace PhpParser;
4
 
5
use PhpParser\Internal\DiffElem;
6
use PhpParser\Internal\PrintableNewAnonClassNode;
7
use PhpParser\Internal\TokenStream;
8
use PhpParser\Node\Expr;
9
use PhpParser\Node\Expr\AssignOp;
10
use PhpParser\Node\Expr\BinaryOp;
11
use PhpParser\Node\Expr\Cast;
12
use PhpParser\Node\Scalar;
13
use PhpParser\Node\Stmt;
14
 
15
abstract class PrettyPrinterAbstract
16
{
17
    const FIXUP_PREC_LEFT       = 0; // LHS operand affected by precedence
18
    const FIXUP_PREC_RIGHT      = 1; // RHS operand affected by precedence
19
    const FIXUP_CALL_LHS        = 2; // LHS of call
20
    const FIXUP_DEREF_LHS       = 3; // LHS of dereferencing operation
21
    const FIXUP_BRACED_NAME     = 4; // Name operand that may require bracing
22
    const FIXUP_VAR_BRACED_NAME = 5; // Name operand that may require ${} bracing
23
    const FIXUP_ENCAPSED        = 6; // Encapsed string part
24
 
25
    protected $precedenceMap = [
26
        // [precedence, associativity]
27
        // where for precedence -1 is %left, 0 is %nonassoc and 1 is %right
28
        BinaryOp\Pow::class            => [  0,  1],
29
        Expr\BitwiseNot::class         => [ 10,  1],
30
        Expr\PreInc::class             => [ 10,  1],
31
        Expr\PreDec::class             => [ 10,  1],
32
        Expr\PostInc::class            => [ 10, -1],
33
        Expr\PostDec::class            => [ 10, -1],
34
        Expr\UnaryPlus::class          => [ 10,  1],
35
        Expr\UnaryMinus::class         => [ 10,  1],
36
        Cast\Int_::class               => [ 10,  1],
37
        Cast\Double::class             => [ 10,  1],
38
        Cast\String_::class            => [ 10,  1],
39
        Cast\Array_::class             => [ 10,  1],
40
        Cast\Object_::class            => [ 10,  1],
41
        Cast\Bool_::class              => [ 10,  1],
42
        Cast\Unset_::class             => [ 10,  1],
43
        Expr\ErrorSuppress::class      => [ 10,  1],
44
        Expr\Instanceof_::class        => [ 20,  0],
45
        Expr\BooleanNot::class         => [ 30,  1],
46
        BinaryOp\Mul::class            => [ 40, -1],
47
        BinaryOp\Div::class            => [ 40, -1],
48
        BinaryOp\Mod::class            => [ 40, -1],
49
        BinaryOp\Plus::class           => [ 50, -1],
50
        BinaryOp\Minus::class          => [ 50, -1],
51
        BinaryOp\Concat::class         => [ 50, -1],
52
        BinaryOp\ShiftLeft::class      => [ 60, -1],
53
        BinaryOp\ShiftRight::class     => [ 60, -1],
54
        BinaryOp\Smaller::class        => [ 70,  0],
55
        BinaryOp\SmallerOrEqual::class => [ 70,  0],
56
        BinaryOp\Greater::class        => [ 70,  0],
57
        BinaryOp\GreaterOrEqual::class => [ 70,  0],
58
        BinaryOp\Equal::class          => [ 80,  0],
59
        BinaryOp\NotEqual::class       => [ 80,  0],
60
        BinaryOp\Identical::class      => [ 80,  0],
61
        BinaryOp\NotIdentical::class   => [ 80,  0],
62
        BinaryOp\Spaceship::class      => [ 80,  0],
63
        BinaryOp\BitwiseAnd::class     => [ 90, -1],
64
        BinaryOp\BitwiseXor::class     => [100, -1],
65
        BinaryOp\BitwiseOr::class      => [110, -1],
66
        BinaryOp\BooleanAnd::class     => [120, -1],
67
        BinaryOp\BooleanOr::class      => [130, -1],
68
        BinaryOp\Coalesce::class       => [140,  1],
69
        Expr\Ternary::class            => [150,  0],
70
        // parser uses %left for assignments, but they really behave as %right
71
        Expr\Assign::class             => [160,  1],
72
        Expr\AssignRef::class          => [160,  1],
73
        AssignOp\Plus::class           => [160,  1],
74
        AssignOp\Minus::class          => [160,  1],
75
        AssignOp\Mul::class            => [160,  1],
76
        AssignOp\Div::class            => [160,  1],
77
        AssignOp\Concat::class         => [160,  1],
78
        AssignOp\Mod::class            => [160,  1],
79
        AssignOp\BitwiseAnd::class     => [160,  1],
80
        AssignOp\BitwiseOr::class      => [160,  1],
81
        AssignOp\BitwiseXor::class     => [160,  1],
82
        AssignOp\ShiftLeft::class      => [160,  1],
83
        AssignOp\ShiftRight::class     => [160,  1],
84
        AssignOp\Pow::class            => [160,  1],
85
        AssignOp\Coalesce::class       => [160,  1],
86
        Expr\YieldFrom::class          => [165,  1],
87
        Expr\Print_::class             => [168,  1],
88
        BinaryOp\LogicalAnd::class     => [170, -1],
89
        BinaryOp\LogicalXor::class     => [180, -1],
90
        BinaryOp\LogicalOr::class      => [190, -1],
91
        Expr\Include_::class           => [200, -1],
92
    ];
93
 
94
    /** @var int Current indentation level. */
95
    protected $indentLevel;
96
    /** @var string Newline including current indentation. */
97
    protected $nl;
98
    /** @var string Token placed at end of doc string to ensure it is followed by a newline. */
99
    protected $docStringEndToken;
100
    /** @var bool Whether semicolon namespaces can be used (i.e. no global namespace is used) */
101
    protected $canUseSemicolonNamespaces;
102
    /** @var array Pretty printer options */
103
    protected $options;
104
 
105
    /** @var TokenStream Original tokens for use in format-preserving pretty print */
106
    protected $origTokens;
107
    /** @var Internal\Differ Differ for node lists */
108
    protected $nodeListDiffer;
109
    /** @var bool[] Map determining whether a certain character is a label character */
110
    protected $labelCharMap;
111
    /**
112
     * @var int[][] Map from token classes and subnode names to FIXUP_* constants. This is used
113
     *              during format-preserving prints to place additional parens/braces if necessary.
114
     */
115
    protected $fixupMap;
116
    /**
117
     * @var int[][] Map from "{$node->getType()}->{$subNode}" to ['left' => $l, 'right' => $r],
118
     *              where $l and $r specify the token type that needs to be stripped when removing
119
     *              this node.
120
     */
121
    protected $removalMap;
122
    /**
123
     * @var mixed[] Map from "{$node->getType()}->{$subNode}" to [$find, $beforeToken, $extraLeft, $extraRight].
124
     *              $find is an optional token after which the insertion occurs. $extraLeft/Right
125
     *              are optionally added before/after the main insertions.
126
     */
127
    protected $insertionMap;
128
    /**
129
     * @var string[] Map From "{$node->getType()}->{$subNode}" to string that should be inserted
130
     *               between elements of this list subnode.
131
     */
132
    protected $listInsertionMap;
133
    protected $emptyListInsertionMap;
134
    /** @var int[] Map from "{$node->getType()}->{$subNode}" to token before which the modifiers
135
     *             should be reprinted. */
136
    protected $modifierChangeMap;
137
 
138
    /**
139
     * Creates a pretty printer instance using the given options.
140
     *
141
     * Supported options:
142
     *  * bool $shortArraySyntax = false: Whether to use [] instead of array() as the default array
143
     *                                    syntax, if the node does not specify a format.
144
     *
145
     * @param array $options Dictionary of formatting options
146
     */
147
    public function __construct(array $options = []) {
148
        $this->docStringEndToken = '_DOC_STRING_END_' . mt_rand();
149
 
150
        $defaultOptions = ['shortArraySyntax' => false];
151
        $this->options = $options + $defaultOptions;
152
    }
153
 
154
    /**
155
     * Reset pretty printing state.
156
     */
157
    protected function resetState() {
158
        $this->indentLevel = 0;
159
        $this->nl = "\n";
160
        $this->origTokens = null;
161
    }
162
 
163
    /**
164
     * Set indentation level
165
     *
166
     * @param int $level Level in number of spaces
167
     */
168
    protected function setIndentLevel(int $level) {
169
        $this->indentLevel = $level;
170
        $this->nl = "\n" . \str_repeat(' ', $level);
171
    }
172
 
173
    /**
174
     * Increase indentation level.
175
     */
176
    protected function indent() {
177
        $this->indentLevel += 4;
178
        $this->nl .= '    ';
179
    }
180
 
181
    /**
182
     * Decrease indentation level.
183
     */
184
    protected function outdent() {
185
        assert($this->indentLevel >= 4);
186
        $this->indentLevel -= 4;
187
        $this->nl = "\n" . str_repeat(' ', $this->indentLevel);
188
    }
189
 
190
    /**
191
     * Pretty prints an array of statements.
192
     *
193
     * @param Node[] $stmts Array of statements
194
     *
195
     * @return string Pretty printed statements
196
     */
197
    public function prettyPrint(array $stmts) : string {
198
        $this->resetState();
199
        $this->preprocessNodes($stmts);
200
 
201
        return ltrim($this->handleMagicTokens($this->pStmts($stmts, false)));
202
    }
203
 
204
    /**
205
     * Pretty prints an expression.
206
     *
207
     * @param Expr $node Expression node
208
     *
209
     * @return string Pretty printed node
210
     */
211
    public function prettyPrintExpr(Expr $node) : string {
212
        $this->resetState();
213
        return $this->handleMagicTokens($this->p($node));
214
    }
215
 
216
    /**
217
     * Pretty prints a file of statements (includes the opening <?php tag if it is required).
218
     *
219
     * @param Node[] $stmts Array of statements
220
     *
221
     * @return string Pretty printed statements
222
     */
223
    public function prettyPrintFile(array $stmts) : string {
224
        if (!$stmts) {
225
            return "<?php\n\n";
226
        }
227
 
228
        $p = "<?php\n\n" . $this->prettyPrint($stmts);
229
 
230
        if ($stmts[0] instanceof Stmt\InlineHTML) {
231
            $p = preg_replace('/^<\?php\s+\?>\n?/', '', $p);
232
        }
233
        if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) {
234
            $p = preg_replace('/<\?php$/', '', rtrim($p));
235
        }
236
 
237
        return $p;
238
    }
239
 
240
    /**
241
     * Preprocesses the top-level nodes to initialize pretty printer state.
242
     *
243
     * @param Node[] $nodes Array of nodes
244
     */
245
    protected function preprocessNodes(array $nodes) {
246
        /* We can use semicolon-namespaces unless there is a global namespace declaration */
247
        $this->canUseSemicolonNamespaces = true;
248
        foreach ($nodes as $node) {
249
            if ($node instanceof Stmt\Namespace_ && null === $node->name) {
250
                $this->canUseSemicolonNamespaces = false;
251
                break;
252
            }
253
        }
254
    }
255
 
256
    /**
257
     * Handles (and removes) no-indent and doc-string-end tokens.
258
     *
259
     * @param string $str
260
     * @return string
261
     */
262
    protected function handleMagicTokens(string $str) : string {
263
        // Replace doc-string-end tokens with nothing or a newline
264
        $str = str_replace($this->docStringEndToken . ";\n", ";\n", $str);
265
        $str = str_replace($this->docStringEndToken, "\n", $str);
266
 
267
        return $str;
268
    }
269
 
270
    /**
271
     * Pretty prints an array of nodes (statements) and indents them optionally.
272
     *
273
     * @param Node[] $nodes  Array of nodes
274
     * @param bool   $indent Whether to indent the printed nodes
275
     *
276
     * @return string Pretty printed statements
277
     */
278
    protected function pStmts(array $nodes, bool $indent = true) : string {
279
        if ($indent) {
280
            $this->indent();
281
        }
282
 
283
        $result = '';
284
        foreach ($nodes as $node) {
285
            $comments = $node->getComments();
286
            if ($comments) {
287
                $result .= $this->nl . $this->pComments($comments);
288
                if ($node instanceof Stmt\Nop) {
289
                    continue;
290
                }
291
            }
292
 
293
            $result .= $this->nl . $this->p($node);
294
        }
295
 
296
        if ($indent) {
297
            $this->outdent();
298
        }
299
 
300
        return $result;
301
    }
302
 
303
    /**
304
     * Pretty-print an infix operation while taking precedence into account.
305
     *
306
     * @param string $class          Node class of operator
307
     * @param Node   $leftNode       Left-hand side node
308
     * @param string $operatorString String representation of the operator
309
     * @param Node   $rightNode      Right-hand side node
310
     *
311
     * @return string Pretty printed infix operation
312
     */
313
    protected function pInfixOp(string $class, Node $leftNode, string $operatorString, Node $rightNode) : string {
314
        list($precedence, $associativity) = $this->precedenceMap[$class];
315
 
316
        return $this->pPrec($leftNode, $precedence, $associativity, -1)
317
             . $operatorString
318
             . $this->pPrec($rightNode, $precedence, $associativity, 1);
319
    }
320
 
321
    /**
322
     * Pretty-print a prefix operation while taking precedence into account.
323
     *
324
     * @param string $class          Node class of operator
325
     * @param string $operatorString String representation of the operator
326
     * @param Node   $node           Node
327
     *
328
     * @return string Pretty printed prefix operation
329
     */
330
    protected function pPrefixOp(string $class, string $operatorString, Node $node) : string {
331
        list($precedence, $associativity) = $this->precedenceMap[$class];
332
        return $operatorString . $this->pPrec($node, $precedence, $associativity, 1);
333
    }
334
 
335
    /**
336
     * Pretty-print a postfix operation while taking precedence into account.
337
     *
338
     * @param string $class          Node class of operator
339
     * @param string $operatorString String representation of the operator
340
     * @param Node   $node           Node
341
     *
342
     * @return string Pretty printed postfix operation
343
     */
344
    protected function pPostfixOp(string $class, Node $node, string $operatorString) : string {
345
        list($precedence, $associativity) = $this->precedenceMap[$class];
346
        return $this->pPrec($node, $precedence, $associativity, -1) . $operatorString;
347
    }
348
 
349
    /**
350
     * Prints an expression node with the least amount of parentheses necessary to preserve the meaning.
351
     *
352
     * @param Node $node                Node to pretty print
353
     * @param int  $parentPrecedence    Precedence of the parent operator
354
     * @param int  $parentAssociativity Associativity of parent operator
355
     *                                  (-1 is left, 0 is nonassoc, 1 is right)
356
     * @param int  $childPosition       Position of the node relative to the operator
357
     *                                  (-1 is left, 1 is right)
358
     *
359
     * @return string The pretty printed node
360
     */
361
    protected function pPrec(Node $node, int $parentPrecedence, int $parentAssociativity, int $childPosition) : string {
362
        $class = \get_class($node);
363
        if (isset($this->precedenceMap[$class])) {
364
            $childPrecedence = $this->precedenceMap[$class][0];
365
            if ($childPrecedence > $parentPrecedence
366
                || ($parentPrecedence === $childPrecedence && $parentAssociativity !== $childPosition)
367
            ) {
368
                return '(' . $this->p($node) . ')';
369
            }
370
        }
371
 
372
        return $this->p($node);
373
    }
374
 
375
    /**
376
     * Pretty prints an array of nodes and implodes the printed values.
377
     *
378
     * @param Node[] $nodes Array of Nodes to be printed
379
     * @param string $glue  Character to implode with
380
     *
381
     * @return string Imploded pretty printed nodes
382
     */
383
    protected function pImplode(array $nodes, string $glue = '') : string {
384
        $pNodes = [];
385
        foreach ($nodes as $node) {
386
            if (null === $node) {
387
                $pNodes[] = '';
388
            } else {
389
                $pNodes[] = $this->p($node);
390
            }
391
        }
392
 
393
        return implode($glue, $pNodes);
394
    }
395
 
396
    /**
397
     * Pretty prints an array of nodes and implodes the printed values with commas.
398
     *
399
     * @param Node[] $nodes Array of Nodes to be printed
400
     *
401
     * @return string Comma separated pretty printed nodes
402
     */
403
    protected function pCommaSeparated(array $nodes) : string {
404
        return $this->pImplode($nodes, ', ');
405
    }
406
 
407
    /**
408
     * Pretty prints a comma-separated list of nodes in multiline style, including comments.
409
     *
410
     * The result includes a leading newline and one level of indentation (same as pStmts).
411
     *
412
     * @param Node[] $nodes         Array of Nodes to be printed
413
     * @param bool   $trailingComma Whether to use a trailing comma
414
     *
415
     * @return string Comma separated pretty printed nodes in multiline style
416
     */
417
    protected function pCommaSeparatedMultiline(array $nodes, bool $trailingComma) : string {
418
        $this->indent();
419
 
420
        $result = '';
421
        $lastIdx = count($nodes) - 1;
422
        foreach ($nodes as $idx => $node) {
423
            if ($node !== null) {
424
                $comments = $node->getComments();
425
                if ($comments) {
426
                    $result .= $this->nl . $this->pComments($comments);
427
                }
428
 
429
                $result .= $this->nl . $this->p($node);
430
            } else {
431
                $result .= $this->nl;
432
            }
433
            if ($trailingComma || $idx !== $lastIdx) {
434
                $result .= ',';
435
            }
436
        }
437
 
438
        $this->outdent();
439
        return $result;
440
    }
441
 
442
    /**
443
     * Prints reformatted text of the passed comments.
444
     *
445
     * @param Comment[] $comments List of comments
446
     *
447
     * @return string Reformatted text of comments
448
     */
449
    protected function pComments(array $comments) : string {
450
        $formattedComments = [];
451
 
452
        foreach ($comments as $comment) {
453
            $formattedComments[] = str_replace("\n", $this->nl, $comment->getReformattedText());
454
        }
455
 
456
        return implode($this->nl, $formattedComments);
457
    }
458
 
459
    /**
460
     * Perform a format-preserving pretty print of an AST.
461
     *
462
     * The format preservation is best effort. For some changes to the AST the formatting will not
463
     * be preserved (at least not locally).
464
     *
465
     * In order to use this method a number of prerequisites must be satisfied:
466
     *  * The startTokenPos and endTokenPos attributes in the lexer must be enabled.
467
     *  * The CloningVisitor must be run on the AST prior to modification.
468
     *  * The original tokens must be provided, using the getTokens() method on the lexer.
469
     *
470
     * @param Node[] $stmts      Modified AST with links to original AST
471
     * @param Node[] $origStmts  Original AST with token offset information
472
     * @param array  $origTokens Tokens of the original code
473
     *
474
     * @return string
475
     */
476
    public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens) : string {
477
        $this->initializeNodeListDiffer();
478
        $this->initializeLabelCharMap();
479
        $this->initializeFixupMap();
480
        $this->initializeRemovalMap();
481
        $this->initializeInsertionMap();
482
        $this->initializeListInsertionMap();
483
        $this->initializeEmptyListInsertionMap();
484
        $this->initializeModifierChangeMap();
485
 
486
        $this->resetState();
487
        $this->origTokens = new TokenStream($origTokens);
488
 
489
        $this->preprocessNodes($stmts);
490
 
491
        $pos = 0;
492
        $result = $this->pArray($stmts, $origStmts, $pos, 0, 'File', 'stmts', null);
493
        if (null !== $result) {
494
            $result .= $this->origTokens->getTokenCode($pos, count($origTokens), 0);
495
        } else {
496
            // Fallback
497
            // TODO Add <?php properly
498
            $result = "<?php\n" . $this->pStmts($stmts, false);
499
        }
500
 
501
        return ltrim($this->handleMagicTokens($result));
502
    }
503
 
504
    protected function pFallback(Node $node) {
505
        return $this->{'p' . $node->getType()}($node);
506
    }
507
 
508
    /**
509
     * Pretty prints a node.
510
     *
511
     * This method also handles formatting preservation for nodes.
512
     *
513
     * @param Node $node Node to be pretty printed
514
     * @param bool $parentFormatPreserved Whether parent node has preserved formatting
515
     *
516
     * @return string Pretty printed node
517
     */
518
    protected function p(Node $node, $parentFormatPreserved = false) : string {
519
        // No orig tokens means this is a normal pretty print without preservation of formatting
520
        if (!$this->origTokens) {
521
            return $this->{'p' . $node->getType()}($node);
522
        }
523
 
524
        /** @var Node $origNode */
525
        $origNode = $node->getAttribute('origNode');
526
        if (null === $origNode) {
527
            return $this->pFallback($node);
528
        }
529
 
530
        $class = \get_class($node);
531
        \assert($class === \get_class($origNode));
532
 
533
        $startPos = $origNode->getStartTokenPos();
534
        $endPos = $origNode->getEndTokenPos();
535
        \assert($startPos >= 0 && $endPos >= 0);
536
 
537
        $fallbackNode = $node;
538
        if ($node instanceof Expr\New_ && $node->class instanceof Stmt\Class_) {
539
            // Normalize node structure of anonymous classes
540
            $node = PrintableNewAnonClassNode::fromNewNode($node);
541
            $origNode = PrintableNewAnonClassNode::fromNewNode($origNode);
542
        }
543
 
544
        // InlineHTML node does not contain closing and opening PHP tags. If the parent formatting
545
        // is not preserved, then we need to use the fallback code to make sure the tags are
546
        // printed.
547
        if ($node instanceof Stmt\InlineHTML && !$parentFormatPreserved) {
548
            return $this->pFallback($fallbackNode);
549
        }
550
 
551
        $indentAdjustment = $this->indentLevel - $this->origTokens->getIndentationBefore($startPos);
552
 
553
        $type = $node->getType();
554
        $fixupInfo = $this->fixupMap[$class] ?? null;
555
 
556
        $result = '';
557
        $pos = $startPos;
558
        foreach ($node->getSubNodeNames() as $subNodeName) {
559
            $subNode = $node->$subNodeName;
560
            $origSubNode = $origNode->$subNodeName;
561
 
562
            if ((!$subNode instanceof Node && $subNode !== null)
563
                || (!$origSubNode instanceof Node && $origSubNode !== null)
564
            ) {
565
                if ($subNode === $origSubNode) {
566
                    // Unchanged, can reuse old code
567
                    continue;
568
                }
569
 
570
                if (is_array($subNode) && is_array($origSubNode)) {
571
                    // Array subnode changed, we might be able to reconstruct it
572
                    $listResult = $this->pArray(
573
                        $subNode, $origSubNode, $pos, $indentAdjustment, $type, $subNodeName,
574
                        $fixupInfo[$subNodeName] ?? null
575
                    );
576
                    if (null === $listResult) {
577
                        return $this->pFallback($fallbackNode);
578
                    }
579
 
580
                    $result .= $listResult;
581
                    continue;
582
                }
583
 
584
                if (is_int($subNode) && is_int($origSubNode)) {
585
                    // Check if this is a modifier change
586
                    $key = $type . '->' . $subNodeName;
587
                    if (!isset($this->modifierChangeMap[$key])) {
588
                        return $this->pFallback($fallbackNode);
589
                    }
590
 
591
                    $findToken = $this->modifierChangeMap[$key];
592
                    $result .= $this->pModifiers($subNode);
593
                    $pos = $this->origTokens->findRight($pos, $findToken);
594
                    continue;
595
                }
596
 
597
                // If a non-node, non-array subnode changed, we don't be able to do a partial
598
                // reconstructions, as we don't have enough offset information. Pretty print the
599
                // whole node instead.
600
                return $this->pFallback($fallbackNode);
601
            }
602
 
603
            $extraLeft = '';
604
            $extraRight = '';
605
            if ($origSubNode !== null) {
606
                $subStartPos = $origSubNode->getStartTokenPos();
607
                $subEndPos = $origSubNode->getEndTokenPos();
608
                \assert($subStartPos >= 0 && $subEndPos >= 0);
609
            } else {
610
                if ($subNode === null) {
611
                    // Both null, nothing to do
612
                    continue;
613
                }
614
 
615
                // A node has been inserted, check if we have insertion information for it
616
                $key = $type . '->' . $subNodeName;
617
                if (!isset($this->insertionMap[$key])) {
618
                    return $this->pFallback($fallbackNode);
619
                }
620
 
621
                list($findToken, $beforeToken, $extraLeft, $extraRight) = $this->insertionMap[$key];
622
                if (null !== $findToken) {
623
                    $subStartPos = $this->origTokens->findRight($pos, $findToken)
624
                        + (int) !$beforeToken;
625
                } else {
626
                    $subStartPos = $pos;
627
                }
628
 
629
                if (null === $extraLeft && null !== $extraRight) {
630
                    // If inserting on the right only, skipping whitespace looks better
631
                    $subStartPos = $this->origTokens->skipRightWhitespace($subStartPos);
632
                }
633
                $subEndPos = $subStartPos - 1;
634
            }
635
 
636
            if (null === $subNode) {
637
                // A node has been removed, check if we have removal information for it
638
                $key = $type . '->' . $subNodeName;
639
                if (!isset($this->removalMap[$key])) {
640
                    return $this->pFallback($fallbackNode);
641
                }
642
 
643
                // Adjust positions to account for additional tokens that must be skipped
644
                $removalInfo = $this->removalMap[$key];
645
                if (isset($removalInfo['left'])) {
646
                    $subStartPos = $this->origTokens->skipLeft($subStartPos - 1, $removalInfo['left']) + 1;
647
                }
648
                if (isset($removalInfo['right'])) {
649
                    $subEndPos = $this->origTokens->skipRight($subEndPos + 1, $removalInfo['right']) - 1;
650
                }
651
            }
652
 
653
            $result .= $this->origTokens->getTokenCode($pos, $subStartPos, $indentAdjustment);
654
 
655
            if (null !== $subNode) {
656
                $result .= $extraLeft;
657
 
658
                $origIndentLevel = $this->indentLevel;
659
                $this->setIndentLevel($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment);
660
 
661
                // If it's the same node that was previously in this position, it certainly doesn't
662
                // need fixup. It's important to check this here, because our fixup checks are more
663
                // conservative than strictly necessary.
664
                if (isset($fixupInfo[$subNodeName])
665
                    && $subNode->getAttribute('origNode') !== $origSubNode
666
                ) {
667
                    $fixup = $fixupInfo[$subNodeName];
668
                    $res = $this->pFixup($fixup, $subNode, $class, $subStartPos, $subEndPos);
669
                } else {
670
                    $res = $this->p($subNode, true);
671
                }
672
 
673
                $this->safeAppend($result, $res);
674
                $this->setIndentLevel($origIndentLevel);
675
 
676
                $result .= $extraRight;
677
            }
678
 
679
            $pos = $subEndPos + 1;
680
        }
681
 
682
        $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment);
683
        return $result;
684
    }
685
 
686
    /**
687
     * Perform a format-preserving pretty print of an array.
688
     *
689
     * @param array       $nodes            New nodes
690
     * @param array       $origNodes        Original nodes
691
     * @param int         $pos              Current token position (updated by reference)
692
     * @param int         $indentAdjustment Adjustment for indentation
693
     * @param string      $parentNodeType   Type of the containing node.
694
     * @param string      $subNodeName      Name of array subnode.
695
     * @param null|int    $fixup            Fixup information for array item nodes
696
     *
697
     * @return null|string Result of pretty print or null if cannot preserve formatting
698
     */
699
    protected function pArray(
700
        array $nodes, array $origNodes, int &$pos, int $indentAdjustment,
701
        string $parentNodeType, string $subNodeName, $fixup
702
    ) {
703
        $diff = $this->nodeListDiffer->diffWithReplacements($origNodes, $nodes);
704
 
705
        $mapKey = $parentNodeType . '->' . $subNodeName;
706
        $insertStr = $this->listInsertionMap[$mapKey] ?? null;
707
        $isStmtList = $subNodeName === 'stmts';
708
 
709
        $beforeFirstKeepOrReplace = true;
710
        $skipRemovedNode = false;
711
        $delayedAdd = [];
712
        $lastElemIndentLevel = $this->indentLevel;
713
 
714
        $insertNewline = false;
715
        if ($insertStr === "\n") {
716
            $insertStr = '';
717
            $insertNewline = true;
718
        }
719
 
720
        if ($isStmtList && \count($origNodes) === 1 && \count($nodes) !== 1) {
721
            $startPos = $origNodes[0]->getStartTokenPos();
722
            $endPos = $origNodes[0]->getEndTokenPos();
723
            \assert($startPos >= 0 && $endPos >= 0);
724
            if (!$this->origTokens->haveBraces($startPos, $endPos)) {
725
                // This was a single statement without braces, but either additional statements
726
                // have been added, or the single statement has been removed. This requires the
727
                // addition of braces. For now fall back.
728
                // TODO: Try to preserve formatting
729
                return null;
730
            }
731
        }
732
 
733
        $result = '';
734
        foreach ($diff as $i => $diffElem) {
735
            $diffType = $diffElem->type;
736
            /** @var Node|null $arrItem */
737
            $arrItem = $diffElem->new;
738
            /** @var Node|null $origArrItem */
739
            $origArrItem = $diffElem->old;
740
 
741
            if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
742
                $beforeFirstKeepOrReplace = false;
743
 
744
                if ($origArrItem === null || $arrItem === null) {
745
                    // We can only handle the case where both are null
746
                    if ($origArrItem === $arrItem) {
747
                        continue;
748
                    }
749
                    return null;
750
                }
751
 
752
                if (!$arrItem instanceof Node || !$origArrItem instanceof Node) {
753
                    // We can only deal with nodes. This can occur for Names, which use string arrays.
754
                    return null;
755
                }
756
 
757
                $itemStartPos = $origArrItem->getStartTokenPos();
758
                $itemEndPos = $origArrItem->getEndTokenPos();
759
                \assert($itemStartPos >= 0 && $itemEndPos >= 0 && $itemStartPos >= $pos);
760
 
761
                $origIndentLevel = $this->indentLevel;
762
                $lastElemIndentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment;
763
                $this->setIndentLevel($lastElemIndentLevel);
764
 
765
                $comments = $arrItem->getComments();
766
                $origComments = $origArrItem->getComments();
767
                $commentStartPos = $origComments ? $origComments[0]->getStartTokenPos() : $itemStartPos;
768
                \assert($commentStartPos >= 0);
769
 
770
                if ($commentStartPos < $pos) {
771
                    // Comments may be assigned to multiple nodes if they start at the same position.
772
                    // Make sure we don't try to print them multiple times.
773
                    $commentStartPos = $itemStartPos;
774
                }
775
 
776
                if ($skipRemovedNode) {
777
                    if ($isStmtList && ($this->origTokens->haveBracesInRange($pos, $itemStartPos) ||
778
                                        $this->origTokens->haveTagInRange($pos, $itemStartPos))) {
779
                        // We'd remove the brace of a code block.
780
                        // TODO: Preserve formatting.
781
                        $this->setIndentLevel($origIndentLevel);
782
                        return null;
783
                    }
784
                } else {
785
                    $result .= $this->origTokens->getTokenCode(
786
                        $pos, $commentStartPos, $indentAdjustment);
787
                }
788
 
789
                if (!empty($delayedAdd)) {
790
                    /** @var Node $delayedAddNode */
791
                    foreach ($delayedAdd as $delayedAddNode) {
792
                        if ($insertNewline) {
793
                            $delayedAddComments = $delayedAddNode->getComments();
794
                            if ($delayedAddComments) {
795
                                $result .= $this->pComments($delayedAddComments) . $this->nl;
796
                            }
797
                        }
798
 
799
                        $this->safeAppend($result, $this->p($delayedAddNode, true));
800
 
801
                        if ($insertNewline) {
802
                            $result .= $insertStr . $this->nl;
803
                        } else {
804
                            $result .= $insertStr;
805
                        }
806
                    }
807
 
808
                    $delayedAdd = [];
809
                }
810
 
811
                if ($comments !== $origComments) {
812
                    if ($comments) {
813
                        $result .= $this->pComments($comments) . $this->nl;
814
                    }
815
                } else {
816
                    $result .= $this->origTokens->getTokenCode(
817
                        $commentStartPos, $itemStartPos, $indentAdjustment);
818
                }
819
 
820
                // If we had to remove anything, we have done so now.
821
                $skipRemovedNode = false;
822
            } elseif ($diffType === DiffElem::TYPE_ADD) {
823
                if (null === $insertStr) {
824
                    // We don't have insertion information for this list type
825
                    return null;
826
                }
827
 
828
                // We go multiline if the original code was multiline,
829
                // or if it's an array item with a comment above it.
830
                if ($insertStr === ', ' &&
831
                    ($this->isMultiline($origNodes) || $arrItem->getComments())
832
                ) {
833
                    $insertStr = ',';
834
                    $insertNewline = true;
835
                }
836
 
837
                if ($beforeFirstKeepOrReplace) {
838
                    // Will be inserted at the next "replace" or "keep" element
839
                    $delayedAdd[] = $arrItem;
840
                    continue;
841
                }
842
 
843
                $itemStartPos = $pos;
844
                $itemEndPos = $pos - 1;
845
 
846
                $origIndentLevel = $this->indentLevel;
847
                $this->setIndentLevel($lastElemIndentLevel);
848
 
849
                if ($insertNewline) {
850
                    $result .= $insertStr . $this->nl;
851
                    $comments = $arrItem->getComments();
852
                    if ($comments) {
853
                        $result .= $this->pComments($comments) . $this->nl;
854
                    }
855
                } else {
856
                    $result .= $insertStr;
857
                }
858
            } elseif ($diffType === DiffElem::TYPE_REMOVE) {
859
                if (!$origArrItem instanceof Node) {
860
                    // We only support removal for nodes
861
                    return null;
862
                }
863
 
864
                $itemStartPos = $origArrItem->getStartTokenPos();
865
                $itemEndPos = $origArrItem->getEndTokenPos();
866
                \assert($itemStartPos >= 0 && $itemEndPos >= 0);
867
 
868
                // Consider comments part of the node.
869
                $origComments = $origArrItem->getComments();
870
                if ($origComments) {
871
                    $itemStartPos = $origComments[0]->getStartTokenPos();
872
                }
873
 
874
                if ($i === 0) {
875
                    // If we're removing from the start, keep the tokens before the node and drop those after it,
876
                    // instead of the other way around.
877
                    $result .= $this->origTokens->getTokenCode(
878
                        $pos, $itemStartPos, $indentAdjustment);
879
                    $skipRemovedNode = true;
880
                } else {
881
                    if ($isStmtList && ($this->origTokens->haveBracesInRange($pos, $itemStartPos) ||
882
                                        $this->origTokens->haveTagInRange($pos, $itemStartPos))) {
883
                        // We'd remove the brace of a code block.
884
                        // TODO: Preserve formatting.
885
                        return null;
886
                    }
887
                }
888
 
889
                $pos = $itemEndPos + 1;
890
                continue;
891
            } else {
892
                throw new \Exception("Shouldn't happen");
893
            }
894
 
895
            if (null !== $fixup && $arrItem->getAttribute('origNode') !== $origArrItem) {
896
                $res = $this->pFixup($fixup, $arrItem, null, $itemStartPos, $itemEndPos);
897
            } else {
898
                $res = $this->p($arrItem, true);
899
            }
900
            $this->safeAppend($result, $res);
901
 
902
            $this->setIndentLevel($origIndentLevel);
903
            $pos = $itemEndPos + 1;
904
        }
905
 
906
        if ($skipRemovedNode) {
907
            // TODO: Support removing single node.
908
            return null;
909
        }
910
 
911
        if (!empty($delayedAdd)) {
912
            if (!isset($this->emptyListInsertionMap[$mapKey])) {
913
                return null;
914
            }
915
 
916
            list($findToken, $extraLeft, $extraRight) = $this->emptyListInsertionMap[$mapKey];
917
            if (null !== $findToken) {
918
                $insertPos = $this->origTokens->findRight($pos, $findToken) + 1;
919
                $result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment);
920
                $pos = $insertPos;
921
            }
922
 
923
            $first = true;
924
            $result .= $extraLeft;
925
            foreach ($delayedAdd as $delayedAddNode) {
926
                if (!$first) {
927
                    $result .= $insertStr;
928
                    if ($insertNewline) {
929
                        $result .= $this->nl;
930
                    }
931
                }
932
                $result .= $this->p($delayedAddNode, true);
933
                $first = false;
934
            }
935
            $result .= $extraRight === "\n" ? $this->nl : $extraRight;
936
        }
937
 
938
        return $result;
939
    }
940
 
941
    /**
942
     * Print node with fixups.
943
     *
944
     * Fixups here refer to the addition of extra parentheses, braces or other characters, that
945
     * are required to preserve program semantics in a certain context (e.g. to maintain precedence
946
     * or because only certain expressions are allowed in certain places).
947
     *
948
     * @param int         $fixup       Fixup type
949
     * @param Node        $subNode     Subnode to print
950
     * @param string|null $parentClass Class of parent node
951
     * @param int         $subStartPos Original start pos of subnode
952
     * @param int         $subEndPos   Original end pos of subnode
953
     *
954
     * @return string Result of fixed-up print of subnode
955
     */
956
    protected function pFixup(int $fixup, Node $subNode, $parentClass, int $subStartPos, int $subEndPos) : string {
957
        switch ($fixup) {
958
            case self::FIXUP_PREC_LEFT:
959
            case self::FIXUP_PREC_RIGHT:
960
                if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) {
961
                    list($precedence, $associativity) = $this->precedenceMap[$parentClass];
962
                    return $this->pPrec($subNode, $precedence, $associativity,
963
                        $fixup === self::FIXUP_PREC_LEFT ? -1 : 1);
964
                }
965
                break;
966
            case self::FIXUP_CALL_LHS:
967
                if ($this->callLhsRequiresParens($subNode)
968
                    && !$this->origTokens->haveParens($subStartPos, $subEndPos)
969
                ) {
970
                    return '(' . $this->p($subNode) . ')';
971
                }
972
                break;
973
            case self::FIXUP_DEREF_LHS:
974
                if ($this->dereferenceLhsRequiresParens($subNode)
975
                    && !$this->origTokens->haveParens($subStartPos, $subEndPos)
976
                ) {
977
                    return '(' . $this->p($subNode) . ')';
978
                }
979
                break;
980
            case self::FIXUP_BRACED_NAME:
981
            case self::FIXUP_VAR_BRACED_NAME:
982
                if ($subNode instanceof Expr
983
                    && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
984
                ) {
985
                    return ($fixup === self::FIXUP_VAR_BRACED_NAME ? '$' : '')
986
                        . '{' . $this->p($subNode) . '}';
987
                }
988
                break;
989
            case self::FIXUP_ENCAPSED:
990
                if (!$subNode instanceof Scalar\EncapsedStringPart
991
                    && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
992
                ) {
993
                    return '{' . $this->p($subNode) . '}';
994
                }
995
                break;
996
            default:
997
                throw new \Exception('Cannot happen');
998
        }
999
 
1000
        // Nothing special to do
1001
        return $this->p($subNode);
1002
    }
1003
 
1004
    /**
1005
     * Appends to a string, ensuring whitespace between label characters.
1006
     *
1007
     * Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x".
1008
     * Without safeAppend the result would be "echox", which does not preserve semantics.
1009
     *
1010
     * @param string $str
1011
     * @param string $append
1012
     */
1013
    protected function safeAppend(string &$str, string $append) {
1014
        if ($str === "") {
1015
            $str = $append;
1016
            return;
1017
        }
1018
 
1019
        if ($append === "") {
1020
            return;
1021
        }
1022
 
1023
        if (!$this->labelCharMap[$append[0]]
1024
                || !$this->labelCharMap[$str[\strlen($str) - 1]]) {
1025
            $str .= $append;
1026
        } else {
1027
            $str .= " " . $append;
1028
        }
1029
    }
1030
 
1031
    /**
1032
     * Determines whether the LHS of a call must be wrapped in parenthesis.
1033
     *
1034
     * @param Node $node LHS of a call
1035
     *
1036
     * @return bool Whether parentheses are required
1037
     */
1038
    protected function callLhsRequiresParens(Node $node) : bool {
1039
        return !($node instanceof Node\Name
1040
            || $node instanceof Expr\Variable
1041
            || $node instanceof Expr\ArrayDimFetch
1042
            || $node instanceof Expr\FuncCall
1043
            || $node instanceof Expr\MethodCall
1044
            || $node instanceof Expr\NullsafeMethodCall
1045
            || $node instanceof Expr\StaticCall
1046
            || $node instanceof Expr\Array_);
1047
    }
1048
 
1049
    /**
1050
     * Determines whether the LHS of a dereferencing operation must be wrapped in parenthesis.
1051
     *
1052
     * @param Node $node LHS of dereferencing operation
1053
     *
1054
     * @return bool Whether parentheses are required
1055
     */
1056
    protected function dereferenceLhsRequiresParens(Node $node) : bool {
1057
        return !($node instanceof Expr\Variable
1058
            || $node instanceof Node\Name
1059
            || $node instanceof Expr\ArrayDimFetch
1060
            || $node instanceof Expr\PropertyFetch
1061
            || $node instanceof Expr\NullsafePropertyFetch
1062
            || $node instanceof Expr\StaticPropertyFetch
1063
            || $node instanceof Expr\FuncCall
1064
            || $node instanceof Expr\MethodCall
1065
            || $node instanceof Expr\NullsafeMethodCall
1066
            || $node instanceof Expr\StaticCall
1067
            || $node instanceof Expr\Array_
1068
            || $node instanceof Scalar\String_
1069
            || $node instanceof Expr\ConstFetch
1070
            || $node instanceof Expr\ClassConstFetch);
1071
    }
1072
 
1073
    /**
1074
     * Print modifiers, including trailing whitespace.
1075
     *
1076
     * @param int $modifiers Modifier mask to print
1077
     *
1078
     * @return string Printed modifiers
1079
     */
1080
    protected function pModifiers(int $modifiers) {
1081
        return ($modifiers & Stmt\Class_::MODIFIER_PUBLIC    ? 'public '    : '')
1082
             . ($modifiers & Stmt\Class_::MODIFIER_PROTECTED ? 'protected ' : '')
1083
             . ($modifiers & Stmt\Class_::MODIFIER_PRIVATE   ? 'private '   : '')
1084
             . ($modifiers & Stmt\Class_::MODIFIER_STATIC    ? 'static '    : '')
1085
             . ($modifiers & Stmt\Class_::MODIFIER_ABSTRACT  ? 'abstract '  : '')
1086
             . ($modifiers & Stmt\Class_::MODIFIER_FINAL     ? 'final '     : '')
1087
             . ($modifiers & Stmt\Class_::MODIFIER_READONLY  ? 'readonly '  : '');
1088
    }
1089
 
1090
    /**
1091
     * Determine whether a list of nodes uses multiline formatting.
1092
     *
1093
     * @param (Node|null)[] $nodes Node list
1094
     *
1095
     * @return bool Whether multiline formatting is used
1096
     */
1097
    protected function isMultiline(array $nodes) : bool {
1098
        if (\count($nodes) < 2) {
1099
            return false;
1100
        }
1101
 
1102
        $pos = -1;
1103
        foreach ($nodes as $node) {
1104
            if (null === $node) {
1105
                continue;
1106
            }
1107
 
1108
            $endPos = $node->getEndTokenPos() + 1;
1109
            if ($pos >= 0) {
1110
                $text = $this->origTokens->getTokenCode($pos, $endPos, 0);
1111
                if (false === strpos($text, "\n")) {
1112
                    // We require that a newline is present between *every* item. If the formatting
1113
                    // is inconsistent, with only some items having newlines, we don't consider it
1114
                    // as multiline
1115
                    return false;
1116
                }
1117
            }
1118
            $pos = $endPos;
1119
        }
1120
 
1121
        return true;
1122
    }
1123
 
1124
    /**
1125
     * Lazily initializes label char map.
1126
     *
1127
     * The label char map determines whether a certain character may occur in a label.
1128
     */
1129
    protected function initializeLabelCharMap() {
1130
        if ($this->labelCharMap) return;
1131
 
1132
        $this->labelCharMap = [];
1133
        for ($i = 0; $i < 256; $i++) {
1134
            // Since PHP 7.1 The lower range is 0x80. However, we also want to support code for
1135
            // older versions.
1136
            $chr = chr($i);
1137
            $this->labelCharMap[$chr] = $i >= 0x7f || ctype_alnum($chr);
1138
        }
1139
    }
1140
 
1141
    /**
1142
     * Lazily initializes node list differ.
1143
     *
1144
     * The node list differ is used to determine differences between two array subnodes.
1145
     */
1146
    protected function initializeNodeListDiffer() {
1147
        if ($this->nodeListDiffer) return;
1148
 
1149
        $this->nodeListDiffer = new Internal\Differ(function ($a, $b) {
1150
            if ($a instanceof Node && $b instanceof Node) {
1151
                return $a === $b->getAttribute('origNode');
1152
            }
1153
            // Can happen for array destructuring
1154
            return $a === null && $b === null;
1155
        });
1156
    }
1157
 
1158
    /**
1159
     * Lazily initializes fixup map.
1160
     *
1161
     * The fixup map is used to determine whether a certain subnode of a certain node may require
1162
     * some kind of "fixup" operation, e.g. the addition of parenthesis or braces.
1163
     */
1164
    protected function initializeFixupMap() {
1165
        if ($this->fixupMap) return;
1166
 
1167
        $this->fixupMap = [
1168
            Expr\PreInc::class => ['var' => self::FIXUP_PREC_RIGHT],
1169
            Expr\PreDec::class => ['var' => self::FIXUP_PREC_RIGHT],
1170
            Expr\PostInc::class => ['var' => self::FIXUP_PREC_LEFT],
1171
            Expr\PostDec::class => ['var' => self::FIXUP_PREC_LEFT],
1172
            Expr\Instanceof_::class => [
1173
                'expr' => self::FIXUP_PREC_LEFT,
1174
                'class' => self::FIXUP_PREC_RIGHT, // TODO: FIXUP_NEW_VARIABLE
1175
            ],
1176
            Expr\Ternary::class => [
1177
                'cond' => self::FIXUP_PREC_LEFT,
1178
                'else' => self::FIXUP_PREC_RIGHT,
1179
            ],
1180
 
1181
            Expr\FuncCall::class => ['name' => self::FIXUP_CALL_LHS],
1182
            Expr\StaticCall::class => ['class' => self::FIXUP_DEREF_LHS],
1183
            Expr\ArrayDimFetch::class => ['var' => self::FIXUP_DEREF_LHS],
1184
            Expr\ClassConstFetch::class => ['var' => self::FIXUP_DEREF_LHS],
1185
            Expr\New_::class => ['class' => self::FIXUP_DEREF_LHS], // TODO: FIXUP_NEW_VARIABLE
1186
            Expr\MethodCall::class => [
1187
                'var' => self::FIXUP_DEREF_LHS,
1188
                'name' => self::FIXUP_BRACED_NAME,
1189
            ],
1190
            Expr\NullsafeMethodCall::class => [
1191
                'var' => self::FIXUP_DEREF_LHS,
1192
                'name' => self::FIXUP_BRACED_NAME,
1193
            ],
1194
            Expr\StaticPropertyFetch::class => [
1195
                'class' => self::FIXUP_DEREF_LHS,
1196
                'name' => self::FIXUP_VAR_BRACED_NAME,
1197
            ],
1198
            Expr\PropertyFetch::class => [
1199
                'var' => self::FIXUP_DEREF_LHS,
1200
                'name' => self::FIXUP_BRACED_NAME,
1201
            ],
1202
            Expr\NullsafePropertyFetch::class => [
1203
                'var' => self::FIXUP_DEREF_LHS,
1204
                'name' => self::FIXUP_BRACED_NAME,
1205
            ],
1206
            Scalar\Encapsed::class => [
1207
                'parts' => self::FIXUP_ENCAPSED,
1208
            ],
1209
        ];
1210
 
1211
        $binaryOps = [
1212
            BinaryOp\Pow::class, BinaryOp\Mul::class, BinaryOp\Div::class, BinaryOp\Mod::class,
1213
            BinaryOp\Plus::class, BinaryOp\Minus::class, BinaryOp\Concat::class,
1214
            BinaryOp\ShiftLeft::class, BinaryOp\ShiftRight::class, BinaryOp\Smaller::class,
1215
            BinaryOp\SmallerOrEqual::class, BinaryOp\Greater::class, BinaryOp\GreaterOrEqual::class,
1216
            BinaryOp\Equal::class, BinaryOp\NotEqual::class, BinaryOp\Identical::class,
1217
            BinaryOp\NotIdentical::class, BinaryOp\Spaceship::class, BinaryOp\BitwiseAnd::class,
1218
            BinaryOp\BitwiseXor::class, BinaryOp\BitwiseOr::class, BinaryOp\BooleanAnd::class,
1219
            BinaryOp\BooleanOr::class, BinaryOp\Coalesce::class, BinaryOp\LogicalAnd::class,
1220
            BinaryOp\LogicalXor::class, BinaryOp\LogicalOr::class,
1221
        ];
1222
        foreach ($binaryOps as $binaryOp) {
1223
            $this->fixupMap[$binaryOp] = [
1224
                'left' => self::FIXUP_PREC_LEFT,
1225
                'right' => self::FIXUP_PREC_RIGHT
1226
            ];
1227
        }
1228
 
1229
        $assignOps = [
1230
            Expr\Assign::class, Expr\AssignRef::class, AssignOp\Plus::class, AssignOp\Minus::class,
1231
            AssignOp\Mul::class, AssignOp\Div::class, AssignOp\Concat::class, AssignOp\Mod::class,
1232
            AssignOp\BitwiseAnd::class, AssignOp\BitwiseOr::class, AssignOp\BitwiseXor::class,
1233
            AssignOp\ShiftLeft::class, AssignOp\ShiftRight::class, AssignOp\Pow::class, AssignOp\Coalesce::class
1234
        ];
1235
        foreach ($assignOps as $assignOp) {
1236
            $this->fixupMap[$assignOp] = [
1237
                'var' => self::FIXUP_PREC_LEFT,
1238
                'expr' => self::FIXUP_PREC_RIGHT,
1239
            ];
1240
        }
1241
 
1242
        $prefixOps = [
1243
            Expr\BitwiseNot::class, Expr\BooleanNot::class, Expr\UnaryPlus::class, Expr\UnaryMinus::class,
1244
            Cast\Int_::class, Cast\Double::class, Cast\String_::class, Cast\Array_::class,
1245
            Cast\Object_::class, Cast\Bool_::class, Cast\Unset_::class, Expr\ErrorSuppress::class,
1246
            Expr\YieldFrom::class, Expr\Print_::class, Expr\Include_::class,
1247
        ];
1248
        foreach ($prefixOps as $prefixOp) {
1249
            $this->fixupMap[$prefixOp] = ['expr' => self::FIXUP_PREC_RIGHT];
1250
        }
1251
    }
1252
 
1253
    /**
1254
     * Lazily initializes the removal map.
1255
     *
1256
     * The removal map is used to determine which additional tokens should be removed when a
1257
     * certain node is replaced by null.
1258
     */
1259
    protected function initializeRemovalMap() {
1260
        if ($this->removalMap) return;
1261
 
1262
        $stripBoth = ['left' => \T_WHITESPACE, 'right' => \T_WHITESPACE];
1263
        $stripLeft = ['left' => \T_WHITESPACE];
1264
        $stripRight = ['right' => \T_WHITESPACE];
1265
        $stripDoubleArrow = ['right' => \T_DOUBLE_ARROW];
1266
        $stripColon = ['left' => ':'];
1267
        $stripEquals = ['left' => '='];
1268
        $this->removalMap = [
1269
            'Expr_ArrayDimFetch->dim' => $stripBoth,
1270
            'Expr_ArrayItem->key' => $stripDoubleArrow,
1271
            'Expr_ArrowFunction->returnType' => $stripColon,
1272
            'Expr_Closure->returnType' => $stripColon,
1273
            'Expr_Exit->expr' => $stripBoth,
1274
            'Expr_Ternary->if' => $stripBoth,
1275
            'Expr_Yield->key' => $stripDoubleArrow,
1276
            'Expr_Yield->value' => $stripBoth,
1277
            'Param->type' => $stripRight,
1278
            'Param->default' => $stripEquals,
1279
            'Stmt_Break->num' => $stripBoth,
1280
            'Stmt_Catch->var' => $stripLeft,
1281
            'Stmt_ClassMethod->returnType' => $stripColon,
1282
            'Stmt_Class->extends' => ['left' => \T_EXTENDS],
1283
            'Stmt_Enum->scalarType' => $stripColon,
1284
            'Stmt_EnumCase->expr' => $stripEquals,
1285
            'Expr_PrintableNewAnonClass->extends' => ['left' => \T_EXTENDS],
1286
            'Stmt_Continue->num' => $stripBoth,
1287
            'Stmt_Foreach->keyVar' => $stripDoubleArrow,
1288
            'Stmt_Function->returnType' => $stripColon,
1289
            'Stmt_If->else' => $stripLeft,
1290
            'Stmt_Namespace->name' => $stripLeft,
1291
            'Stmt_Property->type' => $stripRight,
1292
            'Stmt_PropertyProperty->default' => $stripEquals,
1293
            'Stmt_Return->expr' => $stripBoth,
1294
            'Stmt_StaticVar->default' => $stripEquals,
1295
            'Stmt_TraitUseAdaptation_Alias->newName' => $stripLeft,
1296
            'Stmt_TryCatch->finally' => $stripLeft,
1297
            // 'Stmt_Case->cond': Replace with "default"
1298
            // 'Stmt_Class->name': Unclear what to do
1299
            // 'Stmt_Declare->stmts': Not a plain node
1300
            // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a plain node
1301
        ];
1302
    }
1303
 
1304
    protected function initializeInsertionMap() {
1305
        if ($this->insertionMap) return;
1306
 
1307
        // TODO: "yield" where both key and value are inserted doesn't work
1308
        // [$find, $beforeToken, $extraLeft, $extraRight]
1309
        $this->insertionMap = [
1310
            'Expr_ArrayDimFetch->dim' => ['[', false, null, null],
1311
            'Expr_ArrayItem->key' => [null, false, null, ' => '],
1312
            'Expr_ArrowFunction->returnType' => [')', false, ' : ', null],
1313
            'Expr_Closure->returnType' => [')', false, ' : ', null],
1314
            'Expr_Ternary->if' => ['?', false, ' ', ' '],
1315
            'Expr_Yield->key' => [\T_YIELD, false, null, ' => '],
1316
            'Expr_Yield->value' => [\T_YIELD, false, ' ', null],
1317
            'Param->type' => [null, false, null, ' '],
1318
            'Param->default' => [null, false, ' = ', null],
1319
            'Stmt_Break->num' => [\T_BREAK, false, ' ', null],
1320
            'Stmt_Catch->var' => [null, false, ' ', null],
1321
            'Stmt_ClassMethod->returnType' => [')', false, ' : ', null],
1322
            'Stmt_Class->extends' => [null, false, ' extends ', null],
1323
            'Stmt_Enum->scalarType' => [null, false, ' : ', null],
1324
            'Stmt_EnumCase->expr' => [null, false, ' = ', null],
1325
            'Expr_PrintableNewAnonClass->extends' => [null, ' extends ', null],
1326
            'Stmt_Continue->num' => [\T_CONTINUE, false, ' ', null],
1327
            'Stmt_Foreach->keyVar' => [\T_AS, false, null, ' => '],
1328
            'Stmt_Function->returnType' => [')', false, ' : ', null],
1329
            'Stmt_If->else' => [null, false, ' ', null],
1330
            'Stmt_Namespace->name' => [\T_NAMESPACE, false, ' ', null],
1331
            'Stmt_Property->type' => [\T_VARIABLE, true, null, ' '],
1332
            'Stmt_PropertyProperty->default' => [null, false, ' = ', null],
1333
            'Stmt_Return->expr' => [\T_RETURN, false, ' ', null],
1334
            'Stmt_StaticVar->default' => [null, false, ' = ', null],
1335
            //'Stmt_TraitUseAdaptation_Alias->newName' => [T_AS, false, ' ', null], // TODO
1336
            'Stmt_TryCatch->finally' => [null, false, ' ', null],
1337
 
1338
            // 'Expr_Exit->expr': Complicated due to optional ()
1339
            // 'Stmt_Case->cond': Conversion from default to case
1340
            // 'Stmt_Class->name': Unclear
1341
            // 'Stmt_Declare->stmts': Not a proper node
1342
            // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a proper node
1343
        ];
1344
    }
1345
 
1346
    protected function initializeListInsertionMap() {
1347
        if ($this->listInsertionMap) return;
1348
 
1349
        $this->listInsertionMap = [
1350
            // special
1351
            //'Expr_ShellExec->parts' => '', // TODO These need to be treated more carefully
1352
            //'Scalar_Encapsed->parts' => '',
1353
            'Stmt_Catch->types' => '|',
1354
            'UnionType->types' => '|',
1355
            'IntersectionType->types' => '&',
1356
            'Stmt_If->elseifs' => ' ',
1357
            'Stmt_TryCatch->catches' => ' ',
1358
 
1359
            // comma-separated lists
1360
            'Expr_Array->items' => ', ',
1361
            'Expr_ArrowFunction->params' => ', ',
1362
            'Expr_Closure->params' => ', ',
1363
            'Expr_Closure->uses' => ', ',
1364
            'Expr_FuncCall->args' => ', ',
1365
            'Expr_Isset->vars' => ', ',
1366
            'Expr_List->items' => ', ',
1367
            'Expr_MethodCall->args' => ', ',
1368
            'Expr_NullsafeMethodCall->args' => ', ',
1369
            'Expr_New->args' => ', ',
1370
            'Expr_PrintableNewAnonClass->args' => ', ',
1371
            'Expr_StaticCall->args' => ', ',
1372
            'Stmt_ClassConst->consts' => ', ',
1373
            'Stmt_ClassMethod->params' => ', ',
1374
            'Stmt_Class->implements' => ', ',
1375
            'Stmt_Enum->implements' => ', ',
1376
            'Expr_PrintableNewAnonClass->implements' => ', ',
1377
            'Stmt_Const->consts' => ', ',
1378
            'Stmt_Declare->declares' => ', ',
1379
            'Stmt_Echo->exprs' => ', ',
1380
            'Stmt_For->init' => ', ',
1381
            'Stmt_For->cond' => ', ',
1382
            'Stmt_For->loop' => ', ',
1383
            'Stmt_Function->params' => ', ',
1384
            'Stmt_Global->vars' => ', ',
1385
            'Stmt_GroupUse->uses' => ', ',
1386
            'Stmt_Interface->extends' => ', ',
1387
            'Stmt_Match->arms' => ', ',
1388
            'Stmt_Property->props' => ', ',
1389
            'Stmt_StaticVar->vars' => ', ',
1390
            'Stmt_TraitUse->traits' => ', ',
1391
            'Stmt_TraitUseAdaptation_Precedence->insteadof' => ', ',
1392
            'Stmt_Unset->vars' => ', ',
1393
            'Stmt_Use->uses' => ', ',
1394
            'MatchArm->conds' => ', ',
1395
            'AttributeGroup->attrs' => ', ',
1396
 
1397
            // statement lists
1398
            'Expr_Closure->stmts' => "\n",
1399
            'Stmt_Case->stmts' => "\n",
1400
            'Stmt_Catch->stmts' => "\n",
1401
            'Stmt_Class->stmts' => "\n",
1402
            'Stmt_Enum->stmts' => "\n",
1403
            'Expr_PrintableNewAnonClass->stmts' => "\n",
1404
            'Stmt_Interface->stmts' => "\n",
1405
            'Stmt_Trait->stmts' => "\n",
1406
            'Stmt_ClassMethod->stmts' => "\n",
1407
            'Stmt_Declare->stmts' => "\n",
1408
            'Stmt_Do->stmts' => "\n",
1409
            'Stmt_ElseIf->stmts' => "\n",
1410
            'Stmt_Else->stmts' => "\n",
1411
            'Stmt_Finally->stmts' => "\n",
1412
            'Stmt_Foreach->stmts' => "\n",
1413
            'Stmt_For->stmts' => "\n",
1414
            'Stmt_Function->stmts' => "\n",
1415
            'Stmt_If->stmts' => "\n",
1416
            'Stmt_Namespace->stmts' => "\n",
1417
            'Stmt_Class->attrGroups' => "\n",
1418
            'Stmt_Enum->attrGroups' => "\n",
1419
            'Stmt_EnumCase->attrGroups' => "\n",
1420
            'Stmt_Interface->attrGroups' => "\n",
1421
            'Stmt_Trait->attrGroups' => "\n",
1422
            'Stmt_Function->attrGroups' => "\n",
1423
            'Stmt_ClassMethod->attrGroups' => "\n",
1424
            'Stmt_ClassConst->attrGroups' => "\n",
1425
            'Stmt_Property->attrGroups' => "\n",
1426
            'Expr_PrintableNewAnonClass->attrGroups' => ' ',
1427
            'Expr_Closure->attrGroups' => ' ',
1428
            'Expr_ArrowFunction->attrGroups' => ' ',
1429
            'Param->attrGroups' => ' ',
1430
            'Stmt_Switch->cases' => "\n",
1431
            'Stmt_TraitUse->adaptations' => "\n",
1432
            'Stmt_TryCatch->stmts' => "\n",
1433
            'Stmt_While->stmts' => "\n",
1434
 
1435
            // dummy for top-level context
1436
            'File->stmts' => "\n",
1437
        ];
1438
    }
1439
 
1440
    protected function initializeEmptyListInsertionMap() {
1441
        if ($this->emptyListInsertionMap) return;
1442
 
1443
        // TODO Insertion into empty statement lists.
1444
 
1445
        // [$find, $extraLeft, $extraRight]
1446
        $this->emptyListInsertionMap = [
1447
            'Expr_ArrowFunction->params' => ['(', '', ''],
1448
            'Expr_Closure->uses' => [')', ' use(', ')'],
1449
            'Expr_Closure->params' => ['(', '', ''],
1450
            'Expr_FuncCall->args' => ['(', '', ''],
1451
            'Expr_MethodCall->args' => ['(', '', ''],
1452
            'Expr_NullsafeMethodCall->args' => ['(', '', ''],
1453
            'Expr_New->args' => ['(', '', ''],
1454
            'Expr_PrintableNewAnonClass->args' => ['(', '', ''],
1455
            'Expr_PrintableNewAnonClass->implements' => [null, ' implements ', ''],
1456
            'Expr_StaticCall->args' => ['(', '', ''],
1457
            'Stmt_Class->implements' => [null, ' implements ', ''],
1458
            'Stmt_Enum->implements' => [null, ' implements ', ''],
1459
            'Stmt_ClassMethod->params' => ['(', '', ''],
1460
            'Stmt_Interface->extends' => [null, ' extends ', ''],
1461
            'Stmt_Function->params' => ['(', '', ''],
1462
            'Stmt_Interface->attrGroups' => [null, '', "\n"],
1463
            'Stmt_Class->attrGroups' => [null, '', "\n"],
1464
            'Stmt_ClassConst->attrGroups' => [null, '', "\n"],
1465
            'Stmt_ClassMethod->attrGroups' => [null, '', "\n"],
1466
            'Stmt_Function->attrGroups' => [null, '', "\n"],
1467
            'Stmt_Property->attrGroups' => [null, '', "\n"],
1468
            'Stmt_Trait->attrGroups' => [null, '', "\n"],
1469
            'Expr_ArrowFunction->attrGroups' => [null, '', ' '],
1470
            'Expr_Closure->attrGroups' => [null, '', ' '],
1471
            'Expr_PrintableNewAnonClass->attrGroups' => [\T_NEW, ' ', ''],
1472
 
1473
            /* These cannot be empty to start with:
1474
             * Expr_Isset->vars
1475
             * Stmt_Catch->types
1476
             * Stmt_Const->consts
1477
             * Stmt_ClassConst->consts
1478
             * Stmt_Declare->declares
1479
             * Stmt_Echo->exprs
1480
             * Stmt_Global->vars
1481
             * Stmt_GroupUse->uses
1482
             * Stmt_Property->props
1483
             * Stmt_StaticVar->vars
1484
             * Stmt_TraitUse->traits
1485
             * Stmt_TraitUseAdaptation_Precedence->insteadof
1486
             * Stmt_Unset->vars
1487
             * Stmt_Use->uses
1488
             * UnionType->types
1489
             */
1490
 
1491
            /* TODO
1492
             * Stmt_If->elseifs
1493
             * Stmt_TryCatch->catches
1494
             * Expr_Array->items
1495
             * Expr_List->items
1496
             * Stmt_For->init
1497
             * Stmt_For->cond
1498
             * Stmt_For->loop
1499
             */
1500
        ];
1501
    }
1502
 
1503
    protected function initializeModifierChangeMap() {
1504
        if ($this->modifierChangeMap) return;
1505
 
1506
        $this->modifierChangeMap = [
1507
            'Stmt_ClassConst->flags' => \T_CONST,
1508
            'Stmt_ClassMethod->flags' => \T_FUNCTION,
1509
            'Stmt_Class->flags' => \T_CLASS,
1510
            'Stmt_Property->flags' => \T_VARIABLE,
1511
            'Param->flags' => \T_VARIABLE,
1512
            //'Stmt_TraitUseAdaptation_Alias->newModifier' => 0, // TODO
1513
        ];
1514
 
1515
        // List of integer subnodes that are not modifiers:
1516
        // Expr_Include->type
1517
        // Stmt_GroupUse->type
1518
        // Stmt_Use->type
1519
        // Stmt_UseUse->type
1520
    }
1521
}