annotate vendor/nikic/php-parser/lib/PhpParser/PrettyPrinterAbstract.php @ 5:12f9dff5fda9 tip

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