PrettyPrinterAbstract.php 52 KB

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