Completed
Branch development (b1b115)
by Johannes
10:28
created

PrettyPrinterAbstract   F

Complexity

Total Complexity 195

Size/Duplication

Total Lines 1318
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 195
dl 0
loc 1318
rs 0.8
c 0
b 0
f 0

How to fix   Complexity   

Complex Class

Complex classes like PrettyPrinterAbstract often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PrettyPrinterAbstract, and based on these observations, apply Extract Interface, too.

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