Chris@13: [ 0, 1], Chris@13: Expr\BitwiseNot::class => [ 10, 1], Chris@13: Expr\PreInc::class => [ 10, 1], Chris@13: Expr\PreDec::class => [ 10, 1], Chris@13: Expr\PostInc::class => [ 10, -1], Chris@13: Expr\PostDec::class => [ 10, -1], Chris@13: Expr\UnaryPlus::class => [ 10, 1], Chris@13: Expr\UnaryMinus::class => [ 10, 1], Chris@13: Cast\Int_::class => [ 10, 1], Chris@13: Cast\Double::class => [ 10, 1], Chris@13: Cast\String_::class => [ 10, 1], Chris@13: Cast\Array_::class => [ 10, 1], Chris@13: Cast\Object_::class => [ 10, 1], Chris@13: Cast\Bool_::class => [ 10, 1], Chris@13: Cast\Unset_::class => [ 10, 1], Chris@13: Expr\ErrorSuppress::class => [ 10, 1], Chris@13: Expr\Instanceof_::class => [ 20, 0], Chris@13: Expr\BooleanNot::class => [ 30, 1], Chris@13: BinaryOp\Mul::class => [ 40, -1], Chris@13: BinaryOp\Div::class => [ 40, -1], Chris@13: BinaryOp\Mod::class => [ 40, -1], Chris@13: BinaryOp\Plus::class => [ 50, -1], Chris@13: BinaryOp\Minus::class => [ 50, -1], Chris@13: BinaryOp\Concat::class => [ 50, -1], Chris@13: BinaryOp\ShiftLeft::class => [ 60, -1], Chris@13: BinaryOp\ShiftRight::class => [ 60, -1], Chris@13: BinaryOp\Smaller::class => [ 70, 0], Chris@13: BinaryOp\SmallerOrEqual::class => [ 70, 0], Chris@13: BinaryOp\Greater::class => [ 70, 0], Chris@13: BinaryOp\GreaterOrEqual::class => [ 70, 0], Chris@13: BinaryOp\Equal::class => [ 80, 0], Chris@13: BinaryOp\NotEqual::class => [ 80, 0], Chris@13: BinaryOp\Identical::class => [ 80, 0], Chris@13: BinaryOp\NotIdentical::class => [ 80, 0], Chris@13: BinaryOp\Spaceship::class => [ 80, 0], Chris@13: BinaryOp\BitwiseAnd::class => [ 90, -1], Chris@13: BinaryOp\BitwiseXor::class => [100, -1], Chris@13: BinaryOp\BitwiseOr::class => [110, -1], Chris@13: BinaryOp\BooleanAnd::class => [120, -1], Chris@13: BinaryOp\BooleanOr::class => [130, -1], Chris@13: BinaryOp\Coalesce::class => [140, 1], Chris@13: Expr\Ternary::class => [150, -1], Chris@0: // parser uses %left for assignments, but they really behave as %right Chris@13: Expr\Assign::class => [160, 1], Chris@13: Expr\AssignRef::class => [160, 1], Chris@13: AssignOp\Plus::class => [160, 1], Chris@13: AssignOp\Minus::class => [160, 1], Chris@13: AssignOp\Mul::class => [160, 1], Chris@13: AssignOp\Div::class => [160, 1], Chris@13: AssignOp\Concat::class => [160, 1], Chris@13: AssignOp\Mod::class => [160, 1], Chris@13: AssignOp\BitwiseAnd::class => [160, 1], Chris@13: AssignOp\BitwiseOr::class => [160, 1], Chris@13: AssignOp\BitwiseXor::class => [160, 1], Chris@13: AssignOp\ShiftLeft::class => [160, 1], Chris@13: AssignOp\ShiftRight::class => [160, 1], Chris@13: AssignOp\Pow::class => [160, 1], Chris@17: AssignOp\Coalesce::class => [160, 1], Chris@13: Expr\YieldFrom::class => [165, 1], Chris@13: Expr\Print_::class => [168, 1], Chris@13: BinaryOp\LogicalAnd::class => [170, -1], Chris@13: BinaryOp\LogicalXor::class => [180, -1], Chris@13: BinaryOp\LogicalOr::class => [190, -1], Chris@13: Expr\Include_::class => [200, -1], Chris@13: ]; Chris@0: Chris@13: /** @var int Current indentation level. */ Chris@13: protected $indentLevel; Chris@13: /** @var string Newline including current indentation. */ Chris@13: protected $nl; Chris@13: /** @var string Token placed at end of doc string to ensure it is followed by a newline. */ Chris@0: protected $docStringEndToken; Chris@13: /** @var bool Whether semicolon namespaces can be used (i.e. no global namespace is used) */ Chris@0: protected $canUseSemicolonNamespaces; Chris@13: /** @var array Pretty printer options */ Chris@0: protected $options; Chris@0: Chris@13: /** @var TokenStream Original tokens for use in format-preserving pretty print */ Chris@13: protected $origTokens; Chris@13: /** @var Internal\Differ Differ for node lists */ Chris@13: protected $nodeListDiffer; Chris@13: /** @var bool[] Map determining whether a certain character is a label character */ Chris@13: protected $labelCharMap; Chris@13: /** Chris@13: * @var int[][] Map from token classes and subnode names to FIXUP_* constants. This is used Chris@13: * during format-preserving prints to place additional parens/braces if necessary. Chris@13: */ Chris@13: protected $fixupMap; Chris@13: /** Chris@13: * @var int[][] Map from "{$node->getType()}->{$subNode}" to ['left' => $l, 'right' => $r], Chris@13: * where $l and $r specify the token type that needs to be stripped when removing Chris@13: * this node. Chris@13: */ Chris@13: protected $removalMap; Chris@13: /** Chris@13: * @var mixed[] Map from "{$node->getType()}->{$subNode}" to [$find, $extraLeft, $extraRight]. Chris@13: * $find is an optional token after which the insertion occurs. $extraLeft/Right Chris@13: * are optionally added before/after the main insertions. Chris@13: */ Chris@13: protected $insertionMap; Chris@13: /** Chris@13: * @var string[] Map From "{$node->getType()}->{$subNode}" to string that should be inserted Chris@13: * between elements of this list subnode. Chris@13: */ Chris@13: protected $listInsertionMap; Chris@13: /** @var int[] Map from "{$node->getType()}->{$subNode}" to token before which the modifiers Chris@13: * should be reprinted. */ Chris@13: protected $modifierChangeMap; Chris@13: Chris@0: /** Chris@0: * Creates a pretty printer instance using the given options. Chris@0: * Chris@0: * Supported options: Chris@0: * * bool $shortArraySyntax = false: Whether to use [] instead of array() as the default array Chris@0: * syntax, if the node does not specify a format. Chris@0: * Chris@0: * @param array $options Dictionary of formatting options Chris@0: */ Chris@0: public function __construct(array $options = []) { Chris@0: $this->docStringEndToken = '_DOC_STRING_END_' . mt_rand(); Chris@0: Chris@0: $defaultOptions = ['shortArraySyntax' => false]; Chris@0: $this->options = $options + $defaultOptions; Chris@0: } Chris@0: Chris@0: /** Chris@13: * Reset pretty printing state. Chris@13: */ Chris@13: protected function resetState() { Chris@13: $this->indentLevel = 0; Chris@13: $this->nl = "\n"; Chris@13: $this->origTokens = null; Chris@13: } Chris@13: Chris@13: /** Chris@13: * Set indentation level Chris@13: * Chris@13: * @param int $level Level in number of spaces Chris@13: */ Chris@13: protected function setIndentLevel(int $level) { Chris@13: $this->indentLevel = $level; Chris@13: $this->nl = "\n" . \str_repeat(' ', $level); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Increase indentation level. Chris@13: */ Chris@13: protected function indent() { Chris@13: $this->indentLevel += 4; Chris@13: $this->nl .= ' '; Chris@13: } Chris@13: Chris@13: /** Chris@13: * Decrease indentation level. Chris@13: */ Chris@13: protected function outdent() { Chris@13: assert($this->indentLevel >= 4); Chris@13: $this->indentLevel -= 4; Chris@13: $this->nl = "\n" . str_repeat(' ', $this->indentLevel); Chris@13: } Chris@13: Chris@13: /** Chris@0: * Pretty prints an array of statements. Chris@0: * Chris@0: * @param Node[] $stmts Array of statements Chris@0: * Chris@0: * @return string Pretty printed statements Chris@0: */ Chris@13: public function prettyPrint(array $stmts) : string { Chris@13: $this->resetState(); Chris@0: $this->preprocessNodes($stmts); Chris@0: Chris@0: return ltrim($this->handleMagicTokens($this->pStmts($stmts, false))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pretty prints an expression. Chris@0: * Chris@0: * @param Expr $node Expression node Chris@0: * Chris@0: * @return string Pretty printed node Chris@0: */ Chris@13: public function prettyPrintExpr(Expr $node) : string { Chris@13: $this->resetState(); Chris@0: return $this->handleMagicTokens($this->p($node)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pretty prints a file of statements (includes the opening prettyPrint($stmts); Chris@0: Chris@0: if ($stmts[0] instanceof Stmt\InlineHTML) { Chris@0: $p = preg_replace('/^<\?php\s+\?>\n?/', '', $p); Chris@0: } Chris@0: if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) { Chris@0: $p = preg_replace('/<\?php$/', '', rtrim($p)); Chris@0: } Chris@0: Chris@0: return $p; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Preprocesses the top-level nodes to initialize pretty printer state. Chris@0: * Chris@0: * @param Node[] $nodes Array of nodes Chris@0: */ Chris@0: protected function preprocessNodes(array $nodes) { Chris@0: /* We can use semicolon-namespaces unless there is a global namespace declaration */ Chris@0: $this->canUseSemicolonNamespaces = true; Chris@0: foreach ($nodes as $node) { Chris@0: if ($node instanceof Stmt\Namespace_ && null === $node->name) { Chris@0: $this->canUseSemicolonNamespaces = false; Chris@13: break; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@13: /** Chris@13: * Handles (and removes) no-indent and doc-string-end tokens. Chris@13: * Chris@13: * @param string $str Chris@13: * @return string Chris@13: */ Chris@13: protected function handleMagicTokens(string $str) : string { Chris@0: // Replace doc-string-end tokens with nothing or a newline Chris@0: $str = str_replace($this->docStringEndToken . ";\n", ";\n", $str); Chris@0: $str = str_replace($this->docStringEndToken, "\n", $str); Chris@0: Chris@0: return $str; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pretty prints an array of nodes (statements) and indents them optionally. Chris@0: * Chris@0: * @param Node[] $nodes Array of nodes Chris@0: * @param bool $indent Whether to indent the printed nodes Chris@0: * Chris@0: * @return string Pretty printed statements Chris@0: */ Chris@13: protected function pStmts(array $nodes, bool $indent = true) : string { Chris@13: if ($indent) { Chris@13: $this->indent(); Chris@13: } Chris@13: Chris@0: $result = ''; Chris@0: foreach ($nodes as $node) { Chris@13: $comments = $node->getComments(); Chris@0: if ($comments) { Chris@13: $result .= $this->nl . $this->pComments($comments); Chris@0: if ($node instanceof Stmt\Nop) { Chris@0: continue; Chris@0: } Chris@0: } Chris@0: Chris@13: $result .= $this->nl . $this->p($node); Chris@0: } Chris@0: Chris@0: if ($indent) { Chris@13: $this->outdent(); Chris@0: } Chris@13: Chris@13: return $result; Chris@0: } Chris@0: Chris@0: /** Chris@13: * Pretty-print an infix operation while taking precedence into account. Chris@0: * Chris@13: * @param string $class Node class of operator Chris@13: * @param Node $leftNode Left-hand side node Chris@13: * @param string $operatorString String representation of the operator Chris@13: * @param Node $rightNode Right-hand side node Chris@0: * Chris@13: * @return string Pretty printed infix operation Chris@0: */ Chris@13: protected function pInfixOp(string $class, Node $leftNode, string $operatorString, Node $rightNode) : string { Chris@13: list($precedence, $associativity) = $this->precedenceMap[$class]; Chris@0: Chris@0: return $this->pPrec($leftNode, $precedence, $associativity, -1) Chris@0: . $operatorString Chris@0: . $this->pPrec($rightNode, $precedence, $associativity, 1); Chris@0: } Chris@0: Chris@13: /** Chris@13: * Pretty-print a prefix operation while taking precedence into account. Chris@13: * Chris@13: * @param string $class Node class of operator Chris@13: * @param string $operatorString String representation of the operator Chris@13: * @param Node $node Node Chris@13: * Chris@13: * @return string Pretty printed prefix operation Chris@13: */ Chris@13: protected function pPrefixOp(string $class, string $operatorString, Node $node) : string { Chris@13: list($precedence, $associativity) = $this->precedenceMap[$class]; Chris@0: return $operatorString . $this->pPrec($node, $precedence, $associativity, 1); Chris@0: } Chris@0: Chris@13: /** Chris@13: * Pretty-print a postfix operation while taking precedence into account. Chris@13: * Chris@13: * @param string $class Node class of operator Chris@13: * @param string $operatorString String representation of the operator Chris@13: * @param Node $node Node Chris@13: * Chris@13: * @return string Pretty printed postfix operation Chris@13: */ Chris@13: protected function pPostfixOp(string $class, Node $node, string $operatorString) : string { Chris@13: list($precedence, $associativity) = $this->precedenceMap[$class]; Chris@0: return $this->pPrec($node, $precedence, $associativity, -1) . $operatorString; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prints an expression node with the least amount of parentheses necessary to preserve the meaning. Chris@0: * Chris@0: * @param Node $node Node to pretty print Chris@0: * @param int $parentPrecedence Precedence of the parent operator Chris@0: * @param int $parentAssociativity Associativity of parent operator Chris@0: * (-1 is left, 0 is nonassoc, 1 is right) Chris@0: * @param int $childPosition Position of the node relative to the operator Chris@0: * (-1 is left, 1 is right) Chris@0: * Chris@0: * @return string The pretty printed node Chris@0: */ Chris@13: protected function pPrec(Node $node, int $parentPrecedence, int $parentAssociativity, int $childPosition) : string { Chris@13: $class = \get_class($node); Chris@13: if (isset($this->precedenceMap[$class])) { Chris@13: $childPrecedence = $this->precedenceMap[$class][0]; Chris@0: if ($childPrecedence > $parentPrecedence Chris@13: || ($parentPrecedence === $childPrecedence && $parentAssociativity !== $childPosition) Chris@0: ) { Chris@0: return '(' . $this->p($node) . ')'; Chris@0: } Chris@0: } Chris@0: Chris@0: return $this->p($node); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pretty prints an array of nodes and implodes the printed values. Chris@0: * Chris@0: * @param Node[] $nodes Array of Nodes to be printed Chris@0: * @param string $glue Character to implode with Chris@0: * Chris@0: * @return string Imploded pretty printed nodes Chris@0: */ Chris@13: protected function pImplode(array $nodes, string $glue = '') : string { Chris@13: $pNodes = []; Chris@0: foreach ($nodes as $node) { Chris@0: if (null === $node) { Chris@0: $pNodes[] = ''; Chris@0: } else { Chris@0: $pNodes[] = $this->p($node); Chris@0: } Chris@0: } Chris@0: Chris@0: return implode($glue, $pNodes); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pretty prints an array of nodes and implodes the printed values with commas. Chris@0: * Chris@0: * @param Node[] $nodes Array of Nodes to be printed Chris@0: * Chris@0: * @return string Comma separated pretty printed nodes Chris@0: */ Chris@13: protected function pCommaSeparated(array $nodes) : string { Chris@0: return $this->pImplode($nodes, ', '); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Pretty prints a comma-separated list of nodes in multiline style, including comments. Chris@0: * Chris@0: * The result includes a leading newline and one level of indentation (same as pStmts). Chris@0: * Chris@0: * @param Node[] $nodes Array of Nodes to be printed Chris@0: * @param bool $trailingComma Whether to use a trailing comma Chris@0: * Chris@0: * @return string Comma separated pretty printed nodes in multiline style Chris@0: */ Chris@13: protected function pCommaSeparatedMultiline(array $nodes, bool $trailingComma) : string { Chris@13: $this->indent(); Chris@13: Chris@0: $result = ''; Chris@0: $lastIdx = count($nodes) - 1; Chris@0: foreach ($nodes as $idx => $node) { Chris@0: if ($node !== null) { Chris@13: $comments = $node->getComments(); Chris@0: if ($comments) { Chris@13: $result .= $this->nl . $this->pComments($comments); Chris@0: } Chris@0: Chris@13: $result .= $this->nl . $this->p($node); Chris@0: } else { Chris@13: $result .= $this->nl; Chris@0: } Chris@0: if ($trailingComma || $idx !== $lastIdx) { Chris@0: $result .= ','; Chris@0: } Chris@0: } Chris@0: Chris@13: $this->outdent(); Chris@13: return $result; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Prints reformatted text of the passed comments. Chris@0: * Chris@0: * @param Comment[] $comments List of comments Chris@0: * Chris@0: * @return string Reformatted text of comments Chris@0: */ Chris@13: protected function pComments(array $comments) : string { Chris@0: $formattedComments = []; Chris@0: Chris@0: foreach ($comments as $comment) { Chris@13: $formattedComments[] = str_replace("\n", $this->nl, $comment->getReformattedText()); Chris@0: } Chris@0: Chris@13: return implode($this->nl, $formattedComments); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Perform a format-preserving pretty print of an AST. Chris@13: * Chris@13: * The format preservation is best effort. For some changes to the AST the formatting will not Chris@13: * be preserved (at least not locally). Chris@13: * Chris@13: * In order to use this method a number of prerequisites must be satisfied: Chris@13: * * The startTokenPos and endTokenPos attributes in the lexer must be enabled. Chris@13: * * The CloningVisitor must be run on the AST prior to modification. Chris@13: * * The original tokens must be provided, using the getTokens() method on the lexer. Chris@13: * Chris@13: * @param Node[] $stmts Modified AST with links to original AST Chris@13: * @param Node[] $origStmts Original AST with token offset information Chris@13: * @param array $origTokens Tokens of the original code Chris@13: * Chris@13: * @return string Chris@13: */ Chris@13: public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens) : string { Chris@13: $this->initializeNodeListDiffer(); Chris@13: $this->initializeLabelCharMap(); Chris@13: $this->initializeFixupMap(); Chris@13: $this->initializeRemovalMap(); Chris@13: $this->initializeInsertionMap(); Chris@13: $this->initializeListInsertionMap(); Chris@13: $this->initializeModifierChangeMap(); Chris@13: Chris@13: $this->resetState(); Chris@13: $this->origTokens = new TokenStream($origTokens); Chris@13: Chris@13: $this->preprocessNodes($stmts); Chris@13: Chris@13: $pos = 0; Chris@13: $result = $this->pArray($stmts, $origStmts, $pos, 0, 'stmts', null, "\n"); Chris@13: if (null !== $result) { Chris@13: $result .= $this->origTokens->getTokenCode($pos, count($origTokens), 0); Chris@13: } else { Chris@13: // Fallback Chris@13: // TODO Add pStmts($stmts, false); Chris@13: } Chris@13: Chris@13: return ltrim($this->handleMagicTokens($result)); Chris@13: } Chris@13: Chris@13: protected function pFallback(Node $node) { Chris@13: return $this->{'p' . $node->getType()}($node); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Pretty prints a node. Chris@13: * Chris@13: * This method also handles formatting preservation for nodes. Chris@13: * Chris@13: * @param Node $node Node to be pretty printed Chris@13: * @param bool $parentFormatPreserved Whether parent node has preserved formatting Chris@13: * Chris@13: * @return string Pretty printed node Chris@13: */ Chris@13: protected function p(Node $node, $parentFormatPreserved = false) : string { Chris@13: // No orig tokens means this is a normal pretty print without preservation of formatting Chris@13: if (!$this->origTokens) { Chris@13: return $this->{'p' . $node->getType()}($node); Chris@13: } Chris@13: Chris@13: /** @var Node $origNode */ Chris@13: $origNode = $node->getAttribute('origNode'); Chris@13: if (null === $origNode) { Chris@13: return $this->pFallback($node); Chris@13: } Chris@13: Chris@13: $class = \get_class($node); Chris@13: \assert($class === \get_class($origNode)); Chris@13: Chris@13: $startPos = $origNode->getStartTokenPos(); Chris@13: $endPos = $origNode->getEndTokenPos(); Chris@13: \assert($startPos >= 0 && $endPos >= 0); Chris@13: Chris@13: $fallbackNode = $node; Chris@13: if ($node instanceof Expr\New_ && $node->class instanceof Stmt\Class_) { Chris@13: // Normalize node structure of anonymous classes Chris@13: $node = PrintableNewAnonClassNode::fromNewNode($node); Chris@13: $origNode = PrintableNewAnonClassNode::fromNewNode($origNode); Chris@13: } Chris@13: Chris@13: // InlineHTML node does not contain closing and opening PHP tags. If the parent formatting Chris@13: // is not preserved, then we need to use the fallback code to make sure the tags are Chris@13: // printed. Chris@13: if ($node instanceof Stmt\InlineHTML && !$parentFormatPreserved) { Chris@13: return $this->pFallback($fallbackNode); Chris@13: } Chris@13: Chris@13: $indentAdjustment = $this->indentLevel - $this->origTokens->getIndentationBefore($startPos); Chris@13: Chris@13: $type = $node->getType(); Chris@13: $fixupInfo = $this->fixupMap[$class] ?? null; Chris@13: Chris@13: $result = ''; Chris@13: $pos = $startPos; Chris@13: foreach ($node->getSubNodeNames() as $subNodeName) { Chris@13: $subNode = $node->$subNodeName; Chris@13: $origSubNode = $origNode->$subNodeName; Chris@13: Chris@13: if ((!$subNode instanceof Node && $subNode !== null) Chris@13: || (!$origSubNode instanceof Node && $origSubNode !== null) Chris@13: ) { Chris@13: if ($subNode === $origSubNode) { Chris@13: // Unchanged, can reuse old code Chris@13: continue; Chris@13: } Chris@13: Chris@13: if (is_array($subNode) && is_array($origSubNode)) { Chris@13: // Array subnode changed, we might be able to reconstruct it Chris@13: $listResult = $this->pArray( Chris@13: $subNode, $origSubNode, $pos, $indentAdjustment, $subNodeName, Chris@13: $fixupInfo[$subNodeName] ?? null, Chris@13: $this->listInsertionMap[$type . '->' . $subNodeName] ?? null Chris@13: ); Chris@13: if (null === $listResult) { Chris@13: return $this->pFallback($fallbackNode); Chris@13: } Chris@13: Chris@13: $result .= $listResult; Chris@13: continue; Chris@13: } Chris@13: Chris@13: if (is_int($subNode) && is_int($origSubNode)) { Chris@13: // Check if this is a modifier change Chris@13: $key = $type . '->' . $subNodeName; Chris@13: if (!isset($this->modifierChangeMap[$key])) { Chris@13: return $this->pFallback($fallbackNode); Chris@13: } Chris@13: Chris@13: $findToken = $this->modifierChangeMap[$key]; Chris@13: $result .= $this->pModifiers($subNode); Chris@13: $pos = $this->origTokens->findRight($pos, $findToken); Chris@13: continue; Chris@13: } Chris@13: Chris@13: // If a non-node, non-array subnode changed, we don't be able to do a partial Chris@13: // reconstructions, as we don't have enough offset information. Pretty print the Chris@13: // whole node instead. Chris@13: return $this->pFallback($fallbackNode); Chris@13: } Chris@13: Chris@13: $extraLeft = ''; Chris@13: $extraRight = ''; Chris@13: if ($origSubNode !== null) { Chris@13: $subStartPos = $origSubNode->getStartTokenPos(); Chris@13: $subEndPos = $origSubNode->getEndTokenPos(); Chris@13: \assert($subStartPos >= 0 && $subEndPos >= 0); Chris@13: } else { Chris@13: if ($subNode === null) { Chris@13: // Both null, nothing to do Chris@13: continue; Chris@13: } Chris@13: Chris@13: // A node has been inserted, check if we have insertion information for it Chris@13: $key = $type . '->' . $subNodeName; Chris@13: if (!isset($this->insertionMap[$key])) { Chris@13: return $this->pFallback($fallbackNode); Chris@13: } Chris@13: Chris@17: list($findToken, $beforeToken, $extraLeft, $extraRight) = $this->insertionMap[$key]; Chris@13: if (null !== $findToken) { Chris@17: $subStartPos = $this->origTokens->findRight($pos, $findToken) Chris@17: + (int) !$beforeToken; Chris@13: } else { Chris@13: $subStartPos = $pos; Chris@13: } Chris@17: Chris@13: if (null === $extraLeft && null !== $extraRight) { Chris@13: // If inserting on the right only, skipping whitespace looks better Chris@13: $subStartPos = $this->origTokens->skipRightWhitespace($subStartPos); Chris@13: } Chris@13: $subEndPos = $subStartPos - 1; Chris@13: } Chris@13: Chris@13: if (null === $subNode) { Chris@13: // A node has been removed, check if we have removal information for it Chris@13: $key = $type . '->' . $subNodeName; Chris@13: if (!isset($this->removalMap[$key])) { Chris@13: return $this->pFallback($fallbackNode); Chris@13: } Chris@13: Chris@13: // Adjust positions to account for additional tokens that must be skipped Chris@13: $removalInfo = $this->removalMap[$key]; Chris@13: if (isset($removalInfo['left'])) { Chris@13: $subStartPos = $this->origTokens->skipLeft($subStartPos - 1, $removalInfo['left']) + 1; Chris@13: } Chris@13: if (isset($removalInfo['right'])) { Chris@13: $subEndPos = $this->origTokens->skipRight($subEndPos + 1, $removalInfo['right']) - 1; Chris@13: } Chris@13: } Chris@13: Chris@13: $result .= $this->origTokens->getTokenCode($pos, $subStartPos, $indentAdjustment); Chris@13: Chris@13: if (null !== $subNode) { Chris@13: $result .= $extraLeft; Chris@13: Chris@13: $origIndentLevel = $this->indentLevel; Chris@13: $this->setIndentLevel($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment); Chris@13: Chris@13: // If it's the same node that was previously in this position, it certainly doesn't Chris@13: // need fixup. It's important to check this here, because our fixup checks are more Chris@13: // conservative than strictly necessary. Chris@13: if (isset($fixupInfo[$subNodeName]) Chris@13: && $subNode->getAttribute('origNode') !== $origSubNode Chris@13: ) { Chris@13: $fixup = $fixupInfo[$subNodeName]; Chris@13: $res = $this->pFixup($fixup, $subNode, $class, $subStartPos, $subEndPos); Chris@13: } else { Chris@13: $res = $this->p($subNode, true); Chris@13: } Chris@13: Chris@13: $this->safeAppend($result, $res); Chris@13: $this->setIndentLevel($origIndentLevel); Chris@13: Chris@13: $result .= $extraRight; Chris@13: } Chris@13: Chris@13: $pos = $subEndPos + 1; Chris@13: } Chris@13: Chris@13: $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment); Chris@13: return $result; Chris@13: } Chris@13: Chris@13: /** Chris@13: * Perform a format-preserving pretty print of an array. Chris@13: * Chris@13: * @param array $nodes New nodes Chris@13: * @param array $origNodes Original nodes Chris@13: * @param int $pos Current token position (updated by reference) Chris@13: * @param int $indentAdjustment Adjustment for indentation Chris@13: * @param string $subNodeName Name of array subnode. Chris@13: * @param null|int $fixup Fixup information for array item nodes Chris@13: * @param null|string $insertStr Separator string to use for insertions Chris@13: * Chris@13: * @return null|string Result of pretty print or null if cannot preserve formatting Chris@13: */ Chris@13: protected function pArray( Chris@13: array $nodes, array $origNodes, int &$pos, int $indentAdjustment, Chris@13: string $subNodeName, $fixup, $insertStr Chris@13: ) { Chris@13: $diff = $this->nodeListDiffer->diffWithReplacements($origNodes, $nodes); Chris@13: Chris@13: $beforeFirstKeepOrReplace = true; Chris@13: $delayedAdd = []; Chris@13: $lastElemIndentLevel = $this->indentLevel; Chris@13: Chris@13: $insertNewline = false; Chris@13: if ($insertStr === "\n") { Chris@13: $insertStr = ''; Chris@13: $insertNewline = true; Chris@13: } Chris@13: Chris@13: if ($subNodeName === 'stmts' && \count($origNodes) === 1 && \count($nodes) !== 1) { Chris@13: $startPos = $origNodes[0]->getStartTokenPos(); Chris@13: $endPos = $origNodes[0]->getEndTokenPos(); Chris@13: \assert($startPos >= 0 && $endPos >= 0); Chris@13: if (!$this->origTokens->haveBraces($startPos, $endPos)) { Chris@13: // This was a single statement without braces, but either additional statements Chris@13: // have been added, or the single statement has been removed. This requires the Chris@13: // addition of braces. For now fall back. Chris@13: // TODO: Try to preserve formatting Chris@13: return null; Chris@13: } Chris@13: } Chris@13: Chris@13: $result = ''; Chris@13: foreach ($diff as $i => $diffElem) { Chris@13: $diffType = $diffElem->type; Chris@13: /** @var Node|null $arrItem */ Chris@13: $arrItem = $diffElem->new; Chris@13: /** @var Node|null $origArrItem */ Chris@13: $origArrItem = $diffElem->old; Chris@13: Chris@13: if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) { Chris@13: $beforeFirstKeepOrReplace = false; Chris@13: Chris@13: if ($origArrItem === null || $arrItem === null) { Chris@13: // We can only handle the case where both are null Chris@13: if ($origArrItem === $arrItem) { Chris@13: continue; Chris@13: } Chris@13: return null; Chris@13: } Chris@13: Chris@13: if (!$arrItem instanceof Node || !$origArrItem instanceof Node) { Chris@13: // We can only deal with nodes. This can occur for Names, which use string arrays. Chris@13: return null; Chris@13: } Chris@13: Chris@13: $itemStartPos = $origArrItem->getStartTokenPos(); Chris@13: $itemEndPos = $origArrItem->getEndTokenPos(); Chris@13: \assert($itemStartPos >= 0 && $itemEndPos >= 0); Chris@13: Chris@13: if ($itemEndPos < $itemStartPos) { Chris@13: // End can be before start for Nop nodes, because offsets refer to non-whitespace Chris@13: // locations, which for an "empty" node might result in an inverted order. Chris@13: assert($origArrItem instanceof Stmt\Nop); Chris@13: continue; Chris@13: } Chris@13: Chris@13: $origIndentLevel = $this->indentLevel; Chris@13: $lastElemIndentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment; Chris@13: $this->setIndentLevel($lastElemIndentLevel); Chris@13: Chris@13: $comments = $arrItem->getComments(); Chris@13: $origComments = $origArrItem->getComments(); Chris@13: $commentStartPos = $origComments ? $origComments[0]->getTokenPos() : $itemStartPos; Chris@13: \assert($commentStartPos >= 0); Chris@13: Chris@13: $commentsChanged = $comments !== $origComments; Chris@13: if ($commentsChanged) { Chris@13: // Remove old comments Chris@13: $itemStartPos = $commentStartPos; Chris@13: } Chris@13: Chris@13: if (!empty($delayedAdd)) { Chris@13: $result .= $this->origTokens->getTokenCode( Chris@13: $pos, $commentStartPos, $indentAdjustment); Chris@13: Chris@13: /** @var Node $delayedAddNode */ Chris@13: foreach ($delayedAdd as $delayedAddNode) { Chris@13: if ($insertNewline) { Chris@13: $delayedAddComments = $delayedAddNode->getComments(); Chris@13: if ($delayedAddComments) { Chris@13: $result .= $this->pComments($delayedAddComments) . $this->nl; Chris@13: } Chris@13: } Chris@13: Chris@13: $this->safeAppend($result, $this->p($delayedAddNode, true)); Chris@13: Chris@13: if ($insertNewline) { Chris@13: $result .= $insertStr . $this->nl; Chris@13: } else { Chris@13: $result .= $insertStr; Chris@13: } Chris@13: } Chris@13: Chris@13: $result .= $this->origTokens->getTokenCode( Chris@13: $commentStartPos, $itemStartPos, $indentAdjustment); Chris@13: Chris@13: $delayedAdd = []; Chris@13: } else { Chris@13: $result .= $this->origTokens->getTokenCode( Chris@13: $pos, $itemStartPos, $indentAdjustment); Chris@13: } Chris@13: Chris@13: if ($commentsChanged && $comments) { Chris@13: // Add new comments Chris@13: $result .= $this->pComments($comments) . $this->nl; Chris@13: } Chris@13: } elseif ($diffType === DiffElem::TYPE_ADD) { Chris@13: if (null === $insertStr) { Chris@13: // We don't have insertion information for this list type Chris@13: return null; Chris@13: } Chris@13: Chris@13: if ($insertStr === ', ' && $this->isMultiline($origNodes)) { Chris@13: $insertStr = ','; Chris@13: $insertNewline = true; Chris@13: } Chris@13: Chris@13: if ($beforeFirstKeepOrReplace) { Chris@13: // Will be inserted at the next "replace" or "keep" element Chris@13: $delayedAdd[] = $arrItem; Chris@13: continue; Chris@13: } Chris@13: Chris@13: $itemStartPos = $pos; Chris@13: $itemEndPos = $pos - 1; Chris@13: Chris@13: $origIndentLevel = $this->indentLevel; Chris@13: $this->setIndentLevel($lastElemIndentLevel); Chris@13: Chris@13: if ($insertNewline) { Chris@13: $comments = $arrItem->getComments(); Chris@13: if ($comments) { Chris@13: $result .= $this->nl . $this->pComments($comments); Chris@13: } Chris@13: $result .= $insertStr . $this->nl; Chris@13: } else { Chris@13: $result .= $insertStr; Chris@13: } Chris@13: } elseif ($diffType === DiffElem::TYPE_REMOVE) { Chris@13: if ($i === 0) { Chris@13: // TODO Handle removal at the start Chris@13: return null; Chris@13: } Chris@13: Chris@13: if (!$origArrItem instanceof Node) { Chris@13: // We only support removal for nodes Chris@13: return null; Chris@13: } Chris@13: Chris@13: $itemEndPos = $origArrItem->getEndTokenPos(); Chris@13: \assert($itemEndPos >= 0); Chris@13: Chris@13: $pos = $itemEndPos + 1; Chris@13: continue; Chris@13: } else { Chris@13: throw new \Exception("Shouldn't happen"); Chris@13: } Chris@13: Chris@13: if (null !== $fixup && $arrItem->getAttribute('origNode') !== $origArrItem) { Chris@13: $res = $this->pFixup($fixup, $arrItem, null, $itemStartPos, $itemEndPos); Chris@13: } else { Chris@13: $res = $this->p($arrItem, true); Chris@13: } Chris@13: $this->safeAppend($result, $res); Chris@13: Chris@13: $this->setIndentLevel($origIndentLevel); Chris@13: $pos = $itemEndPos + 1; Chris@13: } Chris@13: Chris@13: if (!empty($delayedAdd)) { Chris@13: // TODO Handle insertion into empty list Chris@13: return null; Chris@13: } Chris@13: Chris@13: return $result; Chris@13: } Chris@13: Chris@13: /** Chris@13: * Print node with fixups. Chris@13: * Chris@13: * Fixups here refer to the addition of extra parentheses, braces or other characters, that Chris@13: * are required to preserve program semantics in a certain context (e.g. to maintain precedence Chris@13: * or because only certain expressions are allowed in certain places). Chris@13: * Chris@13: * @param int $fixup Fixup type Chris@13: * @param Node $subNode Subnode to print Chris@13: * @param string|null $parentClass Class of parent node Chris@13: * @param int $subStartPos Original start pos of subnode Chris@13: * @param int $subEndPos Original end pos of subnode Chris@13: * Chris@13: * @return string Result of fixed-up print of subnode Chris@13: */ Chris@13: protected function pFixup(int $fixup, Node $subNode, $parentClass, int $subStartPos, int $subEndPos) : string { Chris@13: switch ($fixup) { Chris@13: case self::FIXUP_PREC_LEFT: Chris@13: case self::FIXUP_PREC_RIGHT: Chris@13: if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) { Chris@13: list($precedence, $associativity) = $this->precedenceMap[$parentClass]; Chris@13: return $this->pPrec($subNode, $precedence, $associativity, Chris@13: $fixup === self::FIXUP_PREC_LEFT ? -1 : 1); Chris@13: } Chris@13: break; Chris@13: case self::FIXUP_CALL_LHS: Chris@13: if ($this->callLhsRequiresParens($subNode) Chris@13: && !$this->origTokens->haveParens($subStartPos, $subEndPos) Chris@13: ) { Chris@13: return '(' . $this->p($subNode) . ')'; Chris@13: } Chris@13: break; Chris@13: case self::FIXUP_DEREF_LHS: Chris@13: if ($this->dereferenceLhsRequiresParens($subNode) Chris@13: && !$this->origTokens->haveParens($subStartPos, $subEndPos) Chris@13: ) { Chris@13: return '(' . $this->p($subNode) . ')'; Chris@13: } Chris@13: break; Chris@13: case self::FIXUP_BRACED_NAME: Chris@13: case self::FIXUP_VAR_BRACED_NAME: Chris@13: if ($subNode instanceof Expr Chris@13: && !$this->origTokens->haveBraces($subStartPos, $subEndPos) Chris@13: ) { Chris@13: return ($fixup === self::FIXUP_VAR_BRACED_NAME ? '$' : '') Chris@13: . '{' . $this->p($subNode) . '}'; Chris@13: } Chris@13: break; Chris@13: case self::FIXUP_ENCAPSED: Chris@13: if (!$subNode instanceof Scalar\EncapsedStringPart Chris@13: && !$this->origTokens->haveBraces($subStartPos, $subEndPos) Chris@13: ) { Chris@13: return '{' . $this->p($subNode) . '}'; Chris@13: } Chris@13: break; Chris@13: default: Chris@13: throw new \Exception('Cannot happen'); Chris@13: } Chris@13: Chris@13: // Nothing special to do Chris@13: return $this->p($subNode); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Appends to a string, ensuring whitespace between label characters. Chris@13: * Chris@13: * Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x". Chris@13: * Without safeAppend the result would be "echox", which does not preserve semantics. Chris@13: * Chris@13: * @param string $str Chris@13: * @param string $append Chris@13: */ Chris@13: protected function safeAppend(string &$str, string $append) { Chris@13: if ($str === "") { Chris@13: $str = $append; Chris@13: return; Chris@13: } Chris@13: Chris@17: if ($append === "") { Chris@17: return; Chris@17: } Chris@17: Chris@13: if (!$this->labelCharMap[$append[0]] Chris@13: || !$this->labelCharMap[$str[\strlen($str) - 1]]) { Chris@13: $str .= $append; Chris@13: } else { Chris@13: $str .= " " . $append; Chris@13: } Chris@13: } Chris@13: Chris@13: /** Chris@13: * Determines whether the LHS of a call must be wrapped in parenthesis. Chris@13: * Chris@13: * @param Node $node LHS of a call Chris@13: * Chris@13: * @return bool Whether parentheses are required Chris@13: */ Chris@13: protected function callLhsRequiresParens(Node $node) : bool { Chris@13: return !($node instanceof Node\Name Chris@13: || $node instanceof Expr\Variable Chris@13: || $node instanceof Expr\ArrayDimFetch Chris@13: || $node instanceof Expr\FuncCall Chris@13: || $node instanceof Expr\MethodCall Chris@13: || $node instanceof Expr\StaticCall Chris@13: || $node instanceof Expr\Array_); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Determines whether the LHS of a dereferencing operation must be wrapped in parenthesis. Chris@13: * Chris@13: * @param Node $node LHS of dereferencing operation Chris@13: * Chris@13: * @return bool Whether parentheses are required Chris@13: */ Chris@13: protected function dereferenceLhsRequiresParens(Node $node) : bool { Chris@13: return !($node instanceof Expr\Variable Chris@13: || $node instanceof Node\Name Chris@13: || $node instanceof Expr\ArrayDimFetch Chris@13: || $node instanceof Expr\PropertyFetch Chris@13: || $node instanceof Expr\StaticPropertyFetch Chris@13: || $node instanceof Expr\FuncCall Chris@13: || $node instanceof Expr\MethodCall Chris@13: || $node instanceof Expr\StaticCall Chris@13: || $node instanceof Expr\Array_ Chris@13: || $node instanceof Scalar\String_ Chris@13: || $node instanceof Expr\ConstFetch Chris@13: || $node instanceof Expr\ClassConstFetch); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Print modifiers, including trailing whitespace. Chris@13: * Chris@13: * @param int $modifiers Modifier mask to print Chris@13: * Chris@13: * @return string Printed modifiers Chris@13: */ Chris@13: protected function pModifiers(int $modifiers) { Chris@13: return ($modifiers & Stmt\Class_::MODIFIER_PUBLIC ? 'public ' : '') Chris@13: . ($modifiers & Stmt\Class_::MODIFIER_PROTECTED ? 'protected ' : '') Chris@13: . ($modifiers & Stmt\Class_::MODIFIER_PRIVATE ? 'private ' : '') Chris@13: . ($modifiers & Stmt\Class_::MODIFIER_STATIC ? 'static ' : '') Chris@13: . ($modifiers & Stmt\Class_::MODIFIER_ABSTRACT ? 'abstract ' : '') Chris@13: . ($modifiers & Stmt\Class_::MODIFIER_FINAL ? 'final ' : ''); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Determine whether a list of nodes uses multiline formatting. Chris@13: * Chris@13: * @param (Node|null)[] $nodes Node list Chris@13: * Chris@13: * @return bool Whether multiline formatting is used Chris@13: */ Chris@13: protected function isMultiline(array $nodes) : bool { Chris@13: if (\count($nodes) < 2) { Chris@13: return false; Chris@13: } Chris@13: Chris@13: $pos = -1; Chris@13: foreach ($nodes as $node) { Chris@13: if (null === $node) { Chris@13: continue; Chris@13: } Chris@13: Chris@13: $endPos = $node->getEndTokenPos() + 1; Chris@13: if ($pos >= 0) { Chris@13: $text = $this->origTokens->getTokenCode($pos, $endPos, 0); Chris@13: if (false === strpos($text, "\n")) { Chris@13: // We require that a newline is present between *every* item. If the formatting Chris@13: // is inconsistent, with only some items having newlines, we don't consider it Chris@13: // as multiline Chris@13: return false; Chris@13: } Chris@13: } Chris@13: $pos = $endPos; Chris@13: } Chris@13: Chris@13: return true; Chris@13: } Chris@13: Chris@13: /** Chris@13: * Lazily initializes label char map. Chris@13: * Chris@13: * The label char map determines whether a certain character may occur in a label. Chris@13: */ Chris@13: protected function initializeLabelCharMap() { Chris@13: if ($this->labelCharMap) return; Chris@13: Chris@13: $this->labelCharMap = []; Chris@13: for ($i = 0; $i < 256; $i++) { Chris@13: // Since PHP 7.1 The lower range is 0x80. However, we also want to support code for Chris@13: // older versions. Chris@13: $this->labelCharMap[chr($i)] = $i >= 0x7f || ctype_alnum($i); Chris@13: } Chris@13: } Chris@13: Chris@13: /** Chris@13: * Lazily initializes node list differ. Chris@13: * Chris@13: * The node list differ is used to determine differences between two array subnodes. Chris@13: */ Chris@13: protected function initializeNodeListDiffer() { Chris@13: if ($this->nodeListDiffer) return; Chris@13: Chris@13: $this->nodeListDiffer = new Internal\Differ(function ($a, $b) { Chris@13: if ($a instanceof Node && $b instanceof Node) { Chris@13: return $a === $b->getAttribute('origNode'); Chris@13: } Chris@13: // Can happen for array destructuring Chris@13: return $a === null && $b === null; Chris@13: }); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Lazily initializes fixup map. Chris@13: * Chris@13: * The fixup map is used to determine whether a certain subnode of a certain node may require Chris@13: * some kind of "fixup" operation, e.g. the addition of parenthesis or braces. Chris@13: */ Chris@13: protected function initializeFixupMap() { Chris@13: if ($this->fixupMap) return; Chris@13: Chris@13: $this->fixupMap = [ Chris@13: Expr\PreInc::class => ['var' => self::FIXUP_PREC_RIGHT], Chris@13: Expr\PreDec::class => ['var' => self::FIXUP_PREC_RIGHT], Chris@13: Expr\PostInc::class => ['var' => self::FIXUP_PREC_LEFT], Chris@13: Expr\PostDec::class => ['var' => self::FIXUP_PREC_LEFT], Chris@13: Expr\Instanceof_::class => [ Chris@13: 'expr' => self::FIXUP_PREC_LEFT, Chris@13: 'class' => self::FIXUP_PREC_RIGHT, Chris@13: ], Chris@13: Expr\Ternary::class => [ Chris@13: 'cond' => self::FIXUP_PREC_LEFT, Chris@13: 'else' => self::FIXUP_PREC_RIGHT, Chris@13: ], Chris@13: Chris@13: Expr\FuncCall::class => ['name' => self::FIXUP_CALL_LHS], Chris@13: Expr\StaticCall::class => ['class' => self::FIXUP_DEREF_LHS], Chris@13: Expr\ArrayDimFetch::class => ['var' => self::FIXUP_DEREF_LHS], Chris@13: Expr\MethodCall::class => [ Chris@13: 'var' => self::FIXUP_DEREF_LHS, Chris@13: 'name' => self::FIXUP_BRACED_NAME, Chris@13: ], Chris@13: Expr\StaticPropertyFetch::class => [ Chris@13: 'class' => self::FIXUP_DEREF_LHS, Chris@13: 'name' => self::FIXUP_VAR_BRACED_NAME, Chris@13: ], Chris@13: Expr\PropertyFetch::class => [ Chris@13: 'var' => self::FIXUP_DEREF_LHS, Chris@13: 'name' => self::FIXUP_BRACED_NAME, Chris@13: ], Chris@13: Scalar\Encapsed::class => [ Chris@13: 'parts' => self::FIXUP_ENCAPSED, Chris@13: ], Chris@13: ]; Chris@13: Chris@13: $binaryOps = [ Chris@13: BinaryOp\Pow::class, BinaryOp\Mul::class, BinaryOp\Div::class, BinaryOp\Mod::class, Chris@13: BinaryOp\Plus::class, BinaryOp\Minus::class, BinaryOp\Concat::class, Chris@13: BinaryOp\ShiftLeft::class, BinaryOp\ShiftRight::class, BinaryOp\Smaller::class, Chris@13: BinaryOp\SmallerOrEqual::class, BinaryOp\Greater::class, BinaryOp\GreaterOrEqual::class, Chris@13: BinaryOp\Equal::class, BinaryOp\NotEqual::class, BinaryOp\Identical::class, Chris@13: BinaryOp\NotIdentical::class, BinaryOp\Spaceship::class, BinaryOp\BitwiseAnd::class, Chris@13: BinaryOp\BitwiseXor::class, BinaryOp\BitwiseOr::class, BinaryOp\BooleanAnd::class, Chris@13: BinaryOp\BooleanOr::class, BinaryOp\Coalesce::class, BinaryOp\LogicalAnd::class, Chris@13: BinaryOp\LogicalXor::class, BinaryOp\LogicalOr::class, Chris@13: ]; Chris@13: foreach ($binaryOps as $binaryOp) { Chris@13: $this->fixupMap[$binaryOp] = [ Chris@13: 'left' => self::FIXUP_PREC_LEFT, Chris@13: 'right' => self::FIXUP_PREC_RIGHT Chris@13: ]; Chris@13: } Chris@13: Chris@13: $assignOps = [ Chris@13: Expr\Assign::class, Expr\AssignRef::class, AssignOp\Plus::class, AssignOp\Minus::class, Chris@13: AssignOp\Mul::class, AssignOp\Div::class, AssignOp\Concat::class, AssignOp\Mod::class, Chris@13: AssignOp\BitwiseAnd::class, AssignOp\BitwiseOr::class, AssignOp\BitwiseXor::class, Chris@17: AssignOp\ShiftLeft::class, AssignOp\ShiftRight::class, AssignOp\Pow::class, AssignOp\Coalesce::class Chris@13: ]; Chris@13: foreach ($assignOps as $assignOp) { Chris@13: $this->fixupMap[$assignOp] = [ Chris@13: 'var' => self::FIXUP_PREC_LEFT, Chris@13: 'expr' => self::FIXUP_PREC_RIGHT, Chris@13: ]; Chris@13: } Chris@13: Chris@13: $prefixOps = [ Chris@13: Expr\BitwiseNot::class, Expr\BooleanNot::class, Expr\UnaryPlus::class, Expr\UnaryMinus::class, Chris@13: Cast\Int_::class, Cast\Double::class, Cast\String_::class, Cast\Array_::class, Chris@13: Cast\Object_::class, Cast\Bool_::class, Cast\Unset_::class, Expr\ErrorSuppress::class, Chris@13: Expr\YieldFrom::class, Expr\Print_::class, Expr\Include_::class, Chris@13: ]; Chris@13: foreach ($prefixOps as $prefixOp) { Chris@13: $this->fixupMap[$prefixOp] = ['expr' => self::FIXUP_PREC_RIGHT]; Chris@13: } Chris@13: } Chris@13: Chris@13: /** Chris@13: * Lazily initializes the removal map. Chris@13: * Chris@13: * The removal map is used to determine which additional tokens should be returned when a Chris@13: * certain node is replaced by null. Chris@13: */ Chris@13: protected function initializeRemovalMap() { Chris@13: if ($this->removalMap) return; Chris@13: Chris@13: $stripBoth = ['left' => \T_WHITESPACE, 'right' => \T_WHITESPACE]; Chris@13: $stripLeft = ['left' => \T_WHITESPACE]; Chris@13: $stripRight = ['right' => \T_WHITESPACE]; Chris@13: $stripDoubleArrow = ['right' => \T_DOUBLE_ARROW]; Chris@13: $stripColon = ['left' => ':']; Chris@13: $stripEquals = ['left' => '=']; Chris@13: $this->removalMap = [ Chris@13: 'Expr_ArrayDimFetch->dim' => $stripBoth, Chris@13: 'Expr_ArrayItem->key' => $stripDoubleArrow, Chris@13: 'Expr_Closure->returnType' => $stripColon, Chris@13: 'Expr_Exit->expr' => $stripBoth, Chris@13: 'Expr_Ternary->if' => $stripBoth, Chris@13: 'Expr_Yield->key' => $stripDoubleArrow, Chris@13: 'Expr_Yield->value' => $stripBoth, Chris@13: 'Param->type' => $stripRight, Chris@13: 'Param->default' => $stripEquals, Chris@13: 'Stmt_Break->num' => $stripBoth, Chris@13: 'Stmt_ClassMethod->returnType' => $stripColon, Chris@13: 'Stmt_Class->extends' => ['left' => \T_EXTENDS], Chris@13: 'Expr_PrintableNewAnonClass->extends' => ['left' => \T_EXTENDS], Chris@13: 'Stmt_Continue->num' => $stripBoth, Chris@13: 'Stmt_Foreach->keyVar' => $stripDoubleArrow, Chris@13: 'Stmt_Function->returnType' => $stripColon, Chris@13: 'Stmt_If->else' => $stripLeft, Chris@13: 'Stmt_Namespace->name' => $stripLeft, Chris@17: 'Stmt_Property->type' => $stripRight, Chris@13: 'Stmt_PropertyProperty->default' => $stripEquals, Chris@13: 'Stmt_Return->expr' => $stripBoth, Chris@13: 'Stmt_StaticVar->default' => $stripEquals, Chris@13: 'Stmt_TraitUseAdaptation_Alias->newName' => $stripLeft, Chris@13: 'Stmt_TryCatch->finally' => $stripLeft, Chris@13: // 'Stmt_Case->cond': Replace with "default" Chris@13: // 'Stmt_Class->name': Unclear what to do Chris@13: // 'Stmt_Declare->stmts': Not a plain node Chris@13: // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a plain node Chris@13: ]; Chris@13: } Chris@13: Chris@13: protected function initializeInsertionMap() { Chris@13: if ($this->insertionMap) return; Chris@13: Chris@13: // TODO: "yield" where both key and value are inserted doesn't work Chris@13: $this->insertionMap = [ Chris@17: 'Expr_ArrayDimFetch->dim' => ['[', false, null, null], Chris@17: 'Expr_ArrayItem->key' => [null, false, null, ' => '], Chris@17: 'Expr_Closure->returnType' => [')', false, ' : ', null], Chris@17: 'Expr_Ternary->if' => ['?', false, ' ', ' '], Chris@17: 'Expr_Yield->key' => [\T_YIELD, false, null, ' => '], Chris@17: 'Expr_Yield->value' => [\T_YIELD, false, ' ', null], Chris@17: 'Param->type' => [null, false, null, ' '], Chris@17: 'Param->default' => [null, false, ' = ', null], Chris@17: 'Stmt_Break->num' => [\T_BREAK, false, ' ', null], Chris@17: 'Stmt_ClassMethod->returnType' => [')', false, ' : ', null], Chris@17: 'Stmt_Class->extends' => [null, false, ' extends ', null], Chris@13: 'Expr_PrintableNewAnonClass->extends' => [null, ' extends ', null], Chris@17: 'Stmt_Continue->num' => [\T_CONTINUE, false, ' ', null], Chris@17: 'Stmt_Foreach->keyVar' => [\T_AS, false, null, ' => '], Chris@17: 'Stmt_Function->returnType' => [')', false, ' : ', null], Chris@17: 'Stmt_If->else' => [null, false, ' ', null], Chris@17: 'Stmt_Namespace->name' => [\T_NAMESPACE, false, ' ', null], Chris@17: 'Stmt_Property->type' => [\T_VARIABLE, true, null, ' '], Chris@17: 'Stmt_PropertyProperty->default' => [null, false, ' = ', null], Chris@17: 'Stmt_Return->expr' => [\T_RETURN, false, ' ', null], Chris@17: 'Stmt_StaticVar->default' => [null, false, ' = ', null], Chris@17: //'Stmt_TraitUseAdaptation_Alias->newName' => [T_AS, false, ' ', null], // TODO Chris@17: 'Stmt_TryCatch->finally' => [null, false, ' ', null], Chris@13: Chris@13: // 'Expr_Exit->expr': Complicated due to optional () Chris@13: // 'Stmt_Case->cond': Conversion from default to case Chris@13: // 'Stmt_Class->name': Unclear Chris@13: // 'Stmt_Declare->stmts': Not a proper node Chris@13: // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a proper node Chris@13: ]; Chris@13: } Chris@13: Chris@13: protected function initializeListInsertionMap() { Chris@13: if ($this->listInsertionMap) return; Chris@13: Chris@13: $this->listInsertionMap = [ Chris@13: // special Chris@13: //'Expr_ShellExec->parts' => '', // TODO These need to be treated more carefully Chris@13: //'Scalar_Encapsed->parts' => '', Chris@13: 'Stmt_Catch->types' => '|', Chris@13: 'Stmt_If->elseifs' => ' ', Chris@13: 'Stmt_TryCatch->catches' => ' ', Chris@13: Chris@13: // comma-separated lists Chris@13: 'Expr_Array->items' => ', ', Chris@13: 'Expr_Closure->params' => ', ', Chris@13: 'Expr_Closure->uses' => ', ', Chris@13: 'Expr_FuncCall->args' => ', ', Chris@13: 'Expr_Isset->vars' => ', ', Chris@13: 'Expr_List->items' => ', ', Chris@13: 'Expr_MethodCall->args' => ', ', Chris@13: 'Expr_New->args' => ', ', Chris@13: 'Expr_PrintableNewAnonClass->args' => ', ', Chris@13: 'Expr_StaticCall->args' => ', ', Chris@13: 'Stmt_ClassConst->consts' => ', ', Chris@13: 'Stmt_ClassMethod->params' => ', ', Chris@13: 'Stmt_Class->implements' => ', ', Chris@13: 'Expr_PrintableNewAnonClass->implements' => ', ', Chris@13: 'Stmt_Const->consts' => ', ', Chris@13: 'Stmt_Declare->declares' => ', ', Chris@13: 'Stmt_Echo->exprs' => ', ', Chris@13: 'Stmt_For->init' => ', ', Chris@13: 'Stmt_For->cond' => ', ', Chris@13: 'Stmt_For->loop' => ', ', Chris@13: 'Stmt_Function->params' => ', ', Chris@13: 'Stmt_Global->vars' => ', ', Chris@13: 'Stmt_GroupUse->uses' => ', ', Chris@13: 'Stmt_Interface->extends' => ', ', Chris@13: 'Stmt_Property->props' => ', ', Chris@13: 'Stmt_StaticVar->vars' => ', ', Chris@13: 'Stmt_TraitUse->traits' => ', ', Chris@13: 'Stmt_TraitUseAdaptation_Precedence->insteadof' => ', ', Chris@13: 'Stmt_Unset->vars' => ', ', Chris@13: 'Stmt_Use->uses' => ', ', Chris@13: Chris@13: // statement lists Chris@13: 'Expr_Closure->stmts' => "\n", Chris@13: 'Stmt_Case->stmts' => "\n", Chris@13: 'Stmt_Catch->stmts' => "\n", Chris@13: 'Stmt_Class->stmts' => "\n", Chris@13: 'Expr_PrintableNewAnonClass->stmts' => "\n", Chris@13: 'Stmt_Interface->stmts' => "\n", Chris@13: 'Stmt_Trait->stmts' => "\n", Chris@13: 'Stmt_ClassMethod->stmts' => "\n", Chris@13: 'Stmt_Declare->stmts' => "\n", Chris@13: 'Stmt_Do->stmts' => "\n", Chris@13: 'Stmt_ElseIf->stmts' => "\n", Chris@13: 'Stmt_Else->stmts' => "\n", Chris@13: 'Stmt_Finally->stmts' => "\n", Chris@13: 'Stmt_Foreach->stmts' => "\n", Chris@13: 'Stmt_For->stmts' => "\n", Chris@13: 'Stmt_Function->stmts' => "\n", Chris@13: 'Stmt_If->stmts' => "\n", Chris@13: 'Stmt_Namespace->stmts' => "\n", Chris@13: 'Stmt_Switch->cases' => "\n", Chris@13: 'Stmt_TraitUse->adaptations' => "\n", Chris@13: 'Stmt_TryCatch->stmts' => "\n", Chris@13: 'Stmt_While->stmts' => "\n", Chris@13: ]; Chris@13: } Chris@13: Chris@13: protected function initializeModifierChangeMap() { Chris@13: if ($this->modifierChangeMap) return; Chris@13: Chris@13: $this->modifierChangeMap = [ Chris@13: 'Stmt_ClassConst->flags' => \T_CONST, Chris@13: 'Stmt_ClassMethod->flags' => \T_FUNCTION, Chris@13: 'Stmt_Class->flags' => \T_CLASS, Chris@13: 'Stmt_Property->flags' => \T_VARIABLE, Chris@13: //'Stmt_TraitUseAdaptation_Alias->newModifier' => 0, // TODO Chris@13: ]; Chris@13: Chris@13: // List of integer subnodes that are not modifiers: Chris@13: // Expr_Include->type Chris@13: // Stmt_GroupUse->type Chris@13: // Stmt_Use->type Chris@13: // Stmt_UseUse->type Chris@0: } Chris@0: }