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