PrettyPrinterAbstract.php 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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\Scalar;
  11. use PhpParser\Node\Stmt;
  12. abstract class PrettyPrinterAbstract
  13. {
  14. const FIXUP_PREC_LEFT = 0; // LHS operand affected by precedence
  15. const FIXUP_PREC_RIGHT = 1; // RHS operand affected by precedence
  16. const FIXUP_CALL_LHS = 2; // LHS of call
  17. const FIXUP_DEREF_LHS = 3; // LHS of dereferencing operation
  18. const FIXUP_BRACED_NAME = 4; // Name operand that may require bracing
  19. const FIXUP_VAR_BRACED_NAME = 5; // Name operand that may require ${} bracing
  20. const FIXUP_ENCAPSED = 6; // Encapsed string part
  21. protected $precedenceMap = [
  22. // [precedence, associativity]
  23. // where for precedence -1 is %left, 0 is %nonassoc and 1 is %right
  24. BinaryOp\Pow::class => [ 0, 1],
  25. Expr\BitwiseNot::class => [ 10, 1],
  26. Expr\PreInc::class => [ 10, 1],
  27. Expr\PreDec::class => [ 10, 1],
  28. Expr\PostInc::class => [ 10, -1],
  29. Expr\PostDec::class => [ 10, -1],
  30. Expr\UnaryPlus::class => [ 10, 1],
  31. Expr\UnaryMinus::class => [ 10, 1],
  32. Cast\Int_::class => [ 10, 1],
  33. Cast\Double::class => [ 10, 1],
  34. Cast\String_::class => [ 10, 1],
  35. Cast\Array_::class => [ 10, 1],
  36. Cast\Object_::class => [ 10, 1],
  37. Cast\Bool_::class => [ 10, 1],
  38. Cast\Unset_::class => [ 10, 1],
  39. Expr\ErrorSuppress::class => [ 10, 1],
  40. Expr\Instanceof_::class => [ 20, 0],
  41. Expr\BooleanNot::class => [ 30, 1],
  42. BinaryOp\Mul::class => [ 40, -1],
  43. BinaryOp\Div::class => [ 40, -1],
  44. BinaryOp\Mod::class => [ 40, -1],
  45. BinaryOp\Plus::class => [ 50, -1],
  46. BinaryOp\Minus::class => [ 50, -1],
  47. BinaryOp\Concat::class => [ 50, -1],
  48. BinaryOp\ShiftLeft::class => [ 60, -1],
  49. BinaryOp\ShiftRight::class => [ 60, -1],
  50. BinaryOp\Smaller::class => [ 70, 0],
  51. BinaryOp\SmallerOrEqual::class => [ 70, 0],
  52. BinaryOp\Greater::class => [ 70, 0],
  53. BinaryOp\GreaterOrEqual::class => [ 70, 0],
  54. BinaryOp\Equal::class => [ 80, 0],
  55. BinaryOp\NotEqual::class => [ 80, 0],
  56. BinaryOp\Identical::class => [ 80, 0],
  57. BinaryOp\NotIdentical::class => [ 80, 0],
  58. BinaryOp\Spaceship::class => [ 80, 0],
  59. BinaryOp\BitwiseAnd::class => [ 90, -1],
  60. BinaryOp\BitwiseXor::class => [100, -1],
  61. BinaryOp\BitwiseOr::class => [110, -1],
  62. BinaryOp\BooleanAnd::class => [120, -1],
  63. BinaryOp\BooleanOr::class => [130, -1],
  64. BinaryOp\Coalesce::class => [140, 1],
  65. Expr\Ternary::class => [150, -1],
  66. // parser uses %left for assignments, but they really behave as %right
  67. Expr\Assign::class => [160, 1],
  68. Expr\AssignRef::class => [160, 1],
  69. AssignOp\Plus::class => [160, 1],
  70. AssignOp\Minus::class => [160, 1],
  71. AssignOp\Mul::class => [160, 1],
  72. AssignOp\Div::class => [160, 1],
  73. AssignOp\Concat::class => [160, 1],
  74. AssignOp\Mod::class => [160, 1],
  75. AssignOp\BitwiseAnd::class => [160, 1],
  76. AssignOp\BitwiseOr::class => [160, 1],
  77. AssignOp\BitwiseXor::class => [160, 1],
  78. AssignOp\ShiftLeft::class => [160, 1],
  79. AssignOp\ShiftRight::class => [160, 1],
  80. AssignOp\Pow::class => [160, 1],
  81. AssignOp\Coalesce::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, $beforeToken, $extraLeft, $extraRight) = $this->insertionMap[$key];
  554. if (null !== $findToken) {
  555. $subStartPos = $this->origTokens->findRight($pos, $findToken)
  556. + (int) !$beforeToken;
  557. } else {
  558. $subStartPos = $pos;
  559. }
  560. if (null === $extraLeft && null !== $extraRight) {
  561. // If inserting on the right only, skipping whitespace looks better
  562. $subStartPos = $this->origTokens->skipRightWhitespace($subStartPos);
  563. }
  564. $subEndPos = $subStartPos - 1;
  565. }
  566. if (null === $subNode) {
  567. // A node has been removed, check if we have removal information for it
  568. $key = $type . '->' . $subNodeName;
  569. if (!isset($this->removalMap[$key])) {
  570. return $this->pFallback($fallbackNode);
  571. }
  572. // Adjust positions to account for additional tokens that must be skipped
  573. $removalInfo = $this->removalMap[$key];
  574. if (isset($removalInfo['left'])) {
  575. $subStartPos = $this->origTokens->skipLeft($subStartPos - 1, $removalInfo['left']) + 1;
  576. }
  577. if (isset($removalInfo['right'])) {
  578. $subEndPos = $this->origTokens->skipRight($subEndPos + 1, $removalInfo['right']) - 1;
  579. }
  580. }
  581. $result .= $this->origTokens->getTokenCode($pos, $subStartPos, $indentAdjustment);
  582. if (null !== $subNode) {
  583. $result .= $extraLeft;
  584. $origIndentLevel = $this->indentLevel;
  585. $this->setIndentLevel($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment);
  586. // If it's the same node that was previously in this position, it certainly doesn't
  587. // need fixup. It's important to check this here, because our fixup checks are more
  588. // conservative than strictly necessary.
  589. if (isset($fixupInfo[$subNodeName])
  590. && $subNode->getAttribute('origNode') !== $origSubNode
  591. ) {
  592. $fixup = $fixupInfo[$subNodeName];
  593. $res = $this->pFixup($fixup, $subNode, $class, $subStartPos, $subEndPos);
  594. } else {
  595. $res = $this->p($subNode, true);
  596. }
  597. $this->safeAppend($result, $res);
  598. $this->setIndentLevel($origIndentLevel);
  599. $result .= $extraRight;
  600. }
  601. $pos = $subEndPos + 1;
  602. }
  603. $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment);
  604. return $result;
  605. }
  606. /**
  607. * Perform a format-preserving pretty print of an array.
  608. *
  609. * @param array $nodes New nodes
  610. * @param array $origNodes Original nodes
  611. * @param int $pos Current token position (updated by reference)
  612. * @param int $indentAdjustment Adjustment for indentation
  613. * @param string $subNodeName Name of array subnode.
  614. * @param null|int $fixup Fixup information for array item nodes
  615. * @param null|string $insertStr Separator string to use for insertions
  616. *
  617. * @return null|string Result of pretty print or null if cannot preserve formatting
  618. */
  619. protected function pArray(
  620. array $nodes, array $origNodes, int &$pos, int $indentAdjustment,
  621. string $subNodeName, $fixup, $insertStr
  622. ) {
  623. $diff = $this->nodeListDiffer->diffWithReplacements($origNodes, $nodes);
  624. $beforeFirstKeepOrReplace = true;
  625. $delayedAdd = [];
  626. $lastElemIndentLevel = $this->indentLevel;
  627. $insertNewline = false;
  628. if ($insertStr === "\n") {
  629. $insertStr = '';
  630. $insertNewline = true;
  631. }
  632. if ($subNodeName === 'stmts' && \count($origNodes) === 1 && \count($nodes) !== 1) {
  633. $startPos = $origNodes[0]->getStartTokenPos();
  634. $endPos = $origNodes[0]->getEndTokenPos();
  635. \assert($startPos >= 0 && $endPos >= 0);
  636. if (!$this->origTokens->haveBraces($startPos, $endPos)) {
  637. // This was a single statement without braces, but either additional statements
  638. // have been added, or the single statement has been removed. This requires the
  639. // addition of braces. For now fall back.
  640. // TODO: Try to preserve formatting
  641. return null;
  642. }
  643. }
  644. $result = '';
  645. foreach ($diff as $i => $diffElem) {
  646. $diffType = $diffElem->type;
  647. /** @var Node|null $arrItem */
  648. $arrItem = $diffElem->new;
  649. /** @var Node|null $origArrItem */
  650. $origArrItem = $diffElem->old;
  651. if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
  652. $beforeFirstKeepOrReplace = false;
  653. if ($origArrItem === null || $arrItem === null) {
  654. // We can only handle the case where both are null
  655. if ($origArrItem === $arrItem) {
  656. continue;
  657. }
  658. return null;
  659. }
  660. if (!$arrItem instanceof Node || !$origArrItem instanceof Node) {
  661. // We can only deal with nodes. This can occur for Names, which use string arrays.
  662. return null;
  663. }
  664. $itemStartPos = $origArrItem->getStartTokenPos();
  665. $itemEndPos = $origArrItem->getEndTokenPos();
  666. \assert($itemStartPos >= 0 && $itemEndPos >= 0);
  667. if ($itemEndPos < $itemStartPos) {
  668. // End can be before start for Nop nodes, because offsets refer to non-whitespace
  669. // locations, which for an "empty" node might result in an inverted order.
  670. assert($origArrItem instanceof Stmt\Nop);
  671. continue;
  672. }
  673. $origIndentLevel = $this->indentLevel;
  674. $lastElemIndentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment;
  675. $this->setIndentLevel($lastElemIndentLevel);
  676. $comments = $arrItem->getComments();
  677. $origComments = $origArrItem->getComments();
  678. $commentStartPos = $origComments ? $origComments[0]->getTokenPos() : $itemStartPos;
  679. \assert($commentStartPos >= 0);
  680. $commentsChanged = $comments !== $origComments;
  681. if ($commentsChanged) {
  682. // Remove old comments
  683. $itemStartPos = $commentStartPos;
  684. }
  685. if (!empty($delayedAdd)) {
  686. $result .= $this->origTokens->getTokenCode(
  687. $pos, $commentStartPos, $indentAdjustment);
  688. /** @var Node $delayedAddNode */
  689. foreach ($delayedAdd as $delayedAddNode) {
  690. if ($insertNewline) {
  691. $delayedAddComments = $delayedAddNode->getComments();
  692. if ($delayedAddComments) {
  693. $result .= $this->pComments($delayedAddComments) . $this->nl;
  694. }
  695. }
  696. $this->safeAppend($result, $this->p($delayedAddNode, true));
  697. if ($insertNewline) {
  698. $result .= $insertStr . $this->nl;
  699. } else {
  700. $result .= $insertStr;
  701. }
  702. }
  703. $result .= $this->origTokens->getTokenCode(
  704. $commentStartPos, $itemStartPos, $indentAdjustment);
  705. $delayedAdd = [];
  706. } else {
  707. $result .= $this->origTokens->getTokenCode(
  708. $pos, $itemStartPos, $indentAdjustment);
  709. }
  710. if ($commentsChanged && $comments) {
  711. // Add new comments
  712. $result .= $this->pComments($comments) . $this->nl;
  713. }
  714. } elseif ($diffType === DiffElem::TYPE_ADD) {
  715. if (null === $insertStr) {
  716. // We don't have insertion information for this list type
  717. return null;
  718. }
  719. if ($insertStr === ', ' && $this->isMultiline($origNodes)) {
  720. $insertStr = ',';
  721. $insertNewline = true;
  722. }
  723. if ($beforeFirstKeepOrReplace) {
  724. // Will be inserted at the next "replace" or "keep" element
  725. $delayedAdd[] = $arrItem;
  726. continue;
  727. }
  728. $itemStartPos = $pos;
  729. $itemEndPos = $pos - 1;
  730. $origIndentLevel = $this->indentLevel;
  731. $this->setIndentLevel($lastElemIndentLevel);
  732. if ($insertNewline) {
  733. $comments = $arrItem->getComments();
  734. if ($comments) {
  735. $result .= $this->nl . $this->pComments($comments);
  736. }
  737. $result .= $insertStr . $this->nl;
  738. } else {
  739. $result .= $insertStr;
  740. }
  741. } elseif ($diffType === DiffElem::TYPE_REMOVE) {
  742. if ($i === 0) {
  743. // TODO Handle removal at the start
  744. return null;
  745. }
  746. if (!$origArrItem instanceof Node) {
  747. // We only support removal for nodes
  748. return null;
  749. }
  750. $itemEndPos = $origArrItem->getEndTokenPos();
  751. \assert($itemEndPos >= 0);
  752. $pos = $itemEndPos + 1;
  753. continue;
  754. } else {
  755. throw new \Exception("Shouldn't happen");
  756. }
  757. if (null !== $fixup && $arrItem->getAttribute('origNode') !== $origArrItem) {
  758. $res = $this->pFixup($fixup, $arrItem, null, $itemStartPos, $itemEndPos);
  759. } else {
  760. $res = $this->p($arrItem, true);
  761. }
  762. $this->safeAppend($result, $res);
  763. $this->setIndentLevel($origIndentLevel);
  764. $pos = $itemEndPos + 1;
  765. }
  766. if (!empty($delayedAdd)) {
  767. // TODO Handle insertion into empty list
  768. return null;
  769. }
  770. return $result;
  771. }
  772. /**
  773. * Print node with fixups.
  774. *
  775. * Fixups here refer to the addition of extra parentheses, braces or other characters, that
  776. * are required to preserve program semantics in a certain context (e.g. to maintain precedence
  777. * or because only certain expressions are allowed in certain places).
  778. *
  779. * @param int $fixup Fixup type
  780. * @param Node $subNode Subnode to print
  781. * @param string|null $parentClass Class of parent node
  782. * @param int $subStartPos Original start pos of subnode
  783. * @param int $subEndPos Original end pos of subnode
  784. *
  785. * @return string Result of fixed-up print of subnode
  786. */
  787. protected function pFixup(int $fixup, Node $subNode, $parentClass, int $subStartPos, int $subEndPos) : string {
  788. switch ($fixup) {
  789. case self::FIXUP_PREC_LEFT:
  790. case self::FIXUP_PREC_RIGHT:
  791. if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) {
  792. list($precedence, $associativity) = $this->precedenceMap[$parentClass];
  793. return $this->pPrec($subNode, $precedence, $associativity,
  794. $fixup === self::FIXUP_PREC_LEFT ? -1 : 1);
  795. }
  796. break;
  797. case self::FIXUP_CALL_LHS:
  798. if ($this->callLhsRequiresParens($subNode)
  799. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  800. ) {
  801. return '(' . $this->p($subNode) . ')';
  802. }
  803. break;
  804. case self::FIXUP_DEREF_LHS:
  805. if ($this->dereferenceLhsRequiresParens($subNode)
  806. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  807. ) {
  808. return '(' . $this->p($subNode) . ')';
  809. }
  810. break;
  811. case self::FIXUP_BRACED_NAME:
  812. case self::FIXUP_VAR_BRACED_NAME:
  813. if ($subNode instanceof Expr
  814. && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
  815. ) {
  816. return ($fixup === self::FIXUP_VAR_BRACED_NAME ? '$' : '')
  817. . '{' . $this->p($subNode) . '}';
  818. }
  819. break;
  820. case self::FIXUP_ENCAPSED:
  821. if (!$subNode instanceof Scalar\EncapsedStringPart
  822. && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
  823. ) {
  824. return '{' . $this->p($subNode) . '}';
  825. }
  826. break;
  827. default:
  828. throw new \Exception('Cannot happen');
  829. }
  830. // Nothing special to do
  831. return $this->p($subNode);
  832. }
  833. /**
  834. * Appends to a string, ensuring whitespace between label characters.
  835. *
  836. * Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x".
  837. * Without safeAppend the result would be "echox", which does not preserve semantics.
  838. *
  839. * @param string $str
  840. * @param string $append
  841. */
  842. protected function safeAppend(string &$str, string $append) {
  843. if ($str === "") {
  844. $str = $append;
  845. return;
  846. }
  847. if ($append === "") {
  848. return;
  849. }
  850. if (!$this->labelCharMap[$append[0]]
  851. || !$this->labelCharMap[$str[\strlen($str) - 1]]) {
  852. $str .= $append;
  853. } else {
  854. $str .= " " . $append;
  855. }
  856. }
  857. /**
  858. * Determines whether the LHS of a call must be wrapped in parenthesis.
  859. *
  860. * @param Node $node LHS of a call
  861. *
  862. * @return bool Whether parentheses are required
  863. */
  864. protected function callLhsRequiresParens(Node $node) : bool {
  865. return !($node instanceof Node\Name
  866. || $node instanceof Expr\Variable
  867. || $node instanceof Expr\ArrayDimFetch
  868. || $node instanceof Expr\FuncCall
  869. || $node instanceof Expr\MethodCall
  870. || $node instanceof Expr\StaticCall
  871. || $node instanceof Expr\Array_);
  872. }
  873. /**
  874. * Determines whether the LHS of a dereferencing operation must be wrapped in parenthesis.
  875. *
  876. * @param Node $node LHS of dereferencing operation
  877. *
  878. * @return bool Whether parentheses are required
  879. */
  880. protected function dereferenceLhsRequiresParens(Node $node) : bool {
  881. return !($node instanceof Expr\Variable
  882. || $node instanceof Node\Name
  883. || $node instanceof Expr\ArrayDimFetch
  884. || $node instanceof Expr\PropertyFetch
  885. || $node instanceof Expr\StaticPropertyFetch
  886. || $node instanceof Expr\FuncCall
  887. || $node instanceof Expr\MethodCall
  888. || $node instanceof Expr\StaticCall
  889. || $node instanceof Expr\Array_
  890. || $node instanceof Scalar\String_
  891. || $node instanceof Expr\ConstFetch
  892. || $node instanceof Expr\ClassConstFetch);
  893. }
  894. /**
  895. * Print modifiers, including trailing whitespace.
  896. *
  897. * @param int $modifiers Modifier mask to print
  898. *
  899. * @return string Printed modifiers
  900. */
  901. protected function pModifiers(int $modifiers) {
  902. return ($modifiers & Stmt\Class_::MODIFIER_PUBLIC ? 'public ' : '')
  903. . ($modifiers & Stmt\Class_::MODIFIER_PROTECTED ? 'protected ' : '')
  904. . ($modifiers & Stmt\Class_::MODIFIER_PRIVATE ? 'private ' : '')
  905. . ($modifiers & Stmt\Class_::MODIFIER_STATIC ? 'static ' : '')
  906. . ($modifiers & Stmt\Class_::MODIFIER_ABSTRACT ? 'abstract ' : '')
  907. . ($modifiers & Stmt\Class_::MODIFIER_FINAL ? 'final ' : '');
  908. }
  909. /**
  910. * Determine whether a list of nodes uses multiline formatting.
  911. *
  912. * @param (Node|null)[] $nodes Node list
  913. *
  914. * @return bool Whether multiline formatting is used
  915. */
  916. protected function isMultiline(array $nodes) : bool {
  917. if (\count($nodes) < 2) {
  918. return false;
  919. }
  920. $pos = -1;
  921. foreach ($nodes as $node) {
  922. if (null === $node) {
  923. continue;
  924. }
  925. $endPos = $node->getEndTokenPos() + 1;
  926. if ($pos >= 0) {
  927. $text = $this->origTokens->getTokenCode($pos, $endPos, 0);
  928. if (false === strpos($text, "\n")) {
  929. // We require that a newline is present between *every* item. If the formatting
  930. // is inconsistent, with only some items having newlines, we don't consider it
  931. // as multiline
  932. return false;
  933. }
  934. }
  935. $pos = $endPos;
  936. }
  937. return true;
  938. }
  939. /**
  940. * Lazily initializes label char map.
  941. *
  942. * The label char map determines whether a certain character may occur in a label.
  943. */
  944. protected function initializeLabelCharMap() {
  945. if ($this->labelCharMap) return;
  946. $this->labelCharMap = [];
  947. for ($i = 0; $i < 256; $i++) {
  948. // Since PHP 7.1 The lower range is 0x80. However, we also want to support code for
  949. // older versions.
  950. $this->labelCharMap[chr($i)] = $i >= 0x7f || ctype_alnum($i);
  951. }
  952. }
  953. /**
  954. * Lazily initializes node list differ.
  955. *
  956. * The node list differ is used to determine differences between two array subnodes.
  957. */
  958. protected function initializeNodeListDiffer() {
  959. if ($this->nodeListDiffer) return;
  960. $this->nodeListDiffer = new Internal\Differ(function ($a, $b) {
  961. if ($a instanceof Node && $b instanceof Node) {
  962. return $a === $b->getAttribute('origNode');
  963. }
  964. // Can happen for array destructuring
  965. return $a === null && $b === null;
  966. });
  967. }
  968. /**
  969. * Lazily initializes fixup map.
  970. *
  971. * The fixup map is used to determine whether a certain subnode of a certain node may require
  972. * some kind of "fixup" operation, e.g. the addition of parenthesis or braces.
  973. */
  974. protected function initializeFixupMap() {
  975. if ($this->fixupMap) return;
  976. $this->fixupMap = [
  977. Expr\PreInc::class => ['var' => self::FIXUP_PREC_RIGHT],
  978. Expr\PreDec::class => ['var' => self::FIXUP_PREC_RIGHT],
  979. Expr\PostInc::class => ['var' => self::FIXUP_PREC_LEFT],
  980. Expr\PostDec::class => ['var' => self::FIXUP_PREC_LEFT],
  981. Expr\Instanceof_::class => [
  982. 'expr' => self::FIXUP_PREC_LEFT,
  983. 'class' => self::FIXUP_PREC_RIGHT,
  984. ],
  985. Expr\Ternary::class => [
  986. 'cond' => self::FIXUP_PREC_LEFT,
  987. 'else' => self::FIXUP_PREC_RIGHT,
  988. ],
  989. Expr\FuncCall::class => ['name' => self::FIXUP_CALL_LHS],
  990. Expr\StaticCall::class => ['class' => self::FIXUP_DEREF_LHS],
  991. Expr\ArrayDimFetch::class => ['var' => self::FIXUP_DEREF_LHS],
  992. Expr\MethodCall::class => [
  993. 'var' => self::FIXUP_DEREF_LHS,
  994. 'name' => self::FIXUP_BRACED_NAME,
  995. ],
  996. Expr\StaticPropertyFetch::class => [
  997. 'class' => self::FIXUP_DEREF_LHS,
  998. 'name' => self::FIXUP_VAR_BRACED_NAME,
  999. ],
  1000. Expr\PropertyFetch::class => [
  1001. 'var' => self::FIXUP_DEREF_LHS,
  1002. 'name' => self::FIXUP_BRACED_NAME,
  1003. ],
  1004. Scalar\Encapsed::class => [
  1005. 'parts' => self::FIXUP_ENCAPSED,
  1006. ],
  1007. ];
  1008. $binaryOps = [
  1009. BinaryOp\Pow::class, BinaryOp\Mul::class, BinaryOp\Div::class, BinaryOp\Mod::class,
  1010. BinaryOp\Plus::class, BinaryOp\Minus::class, BinaryOp\Concat::class,
  1011. BinaryOp\ShiftLeft::class, BinaryOp\ShiftRight::class, BinaryOp\Smaller::class,
  1012. BinaryOp\SmallerOrEqual::class, BinaryOp\Greater::class, BinaryOp\GreaterOrEqual::class,
  1013. BinaryOp\Equal::class, BinaryOp\NotEqual::class, BinaryOp\Identical::class,
  1014. BinaryOp\NotIdentical::class, BinaryOp\Spaceship::class, BinaryOp\BitwiseAnd::class,
  1015. BinaryOp\BitwiseXor::class, BinaryOp\BitwiseOr::class, BinaryOp\BooleanAnd::class,
  1016. BinaryOp\BooleanOr::class, BinaryOp\Coalesce::class, BinaryOp\LogicalAnd::class,
  1017. BinaryOp\LogicalXor::class, BinaryOp\LogicalOr::class,
  1018. ];
  1019. foreach ($binaryOps as $binaryOp) {
  1020. $this->fixupMap[$binaryOp] = [
  1021. 'left' => self::FIXUP_PREC_LEFT,
  1022. 'right' => self::FIXUP_PREC_RIGHT
  1023. ];
  1024. }
  1025. $assignOps = [
  1026. Expr\Assign::class, Expr\AssignRef::class, AssignOp\Plus::class, AssignOp\Minus::class,
  1027. AssignOp\Mul::class, AssignOp\Div::class, AssignOp\Concat::class, AssignOp\Mod::class,
  1028. AssignOp\BitwiseAnd::class, AssignOp\BitwiseOr::class, AssignOp\BitwiseXor::class,
  1029. AssignOp\ShiftLeft::class, AssignOp\ShiftRight::class, AssignOp\Pow::class, AssignOp\Coalesce::class
  1030. ];
  1031. foreach ($assignOps as $assignOp) {
  1032. $this->fixupMap[$assignOp] = [
  1033. 'var' => self::FIXUP_PREC_LEFT,
  1034. 'expr' => self::FIXUP_PREC_RIGHT,
  1035. ];
  1036. }
  1037. $prefixOps = [
  1038. Expr\BitwiseNot::class, Expr\BooleanNot::class, Expr\UnaryPlus::class, Expr\UnaryMinus::class,
  1039. Cast\Int_::class, Cast\Double::class, Cast\String_::class, Cast\Array_::class,
  1040. Cast\Object_::class, Cast\Bool_::class, Cast\Unset_::class, Expr\ErrorSuppress::class,
  1041. Expr\YieldFrom::class, Expr\Print_::class, Expr\Include_::class,
  1042. ];
  1043. foreach ($prefixOps as $prefixOp) {
  1044. $this->fixupMap[$prefixOp] = ['expr' => self::FIXUP_PREC_RIGHT];
  1045. }
  1046. }
  1047. /**
  1048. * Lazily initializes the removal map.
  1049. *
  1050. * The removal map is used to determine which additional tokens should be returned when a
  1051. * certain node is replaced by null.
  1052. */
  1053. protected function initializeRemovalMap() {
  1054. if ($this->removalMap) return;
  1055. $stripBoth = ['left' => \T_WHITESPACE, 'right' => \T_WHITESPACE];
  1056. $stripLeft = ['left' => \T_WHITESPACE];
  1057. $stripRight = ['right' => \T_WHITESPACE];
  1058. $stripDoubleArrow = ['right' => \T_DOUBLE_ARROW];
  1059. $stripColon = ['left' => ':'];
  1060. $stripEquals = ['left' => '='];
  1061. $this->removalMap = [
  1062. 'Expr_ArrayDimFetch->dim' => $stripBoth,
  1063. 'Expr_ArrayItem->key' => $stripDoubleArrow,
  1064. 'Expr_Closure->returnType' => $stripColon,
  1065. 'Expr_Exit->expr' => $stripBoth,
  1066. 'Expr_Ternary->if' => $stripBoth,
  1067. 'Expr_Yield->key' => $stripDoubleArrow,
  1068. 'Expr_Yield->value' => $stripBoth,
  1069. 'Param->type' => $stripRight,
  1070. 'Param->default' => $stripEquals,
  1071. 'Stmt_Break->num' => $stripBoth,
  1072. 'Stmt_ClassMethod->returnType' => $stripColon,
  1073. 'Stmt_Class->extends' => ['left' => \T_EXTENDS],
  1074. 'Expr_PrintableNewAnonClass->extends' => ['left' => \T_EXTENDS],
  1075. 'Stmt_Continue->num' => $stripBoth,
  1076. 'Stmt_Foreach->keyVar' => $stripDoubleArrow,
  1077. 'Stmt_Function->returnType' => $stripColon,
  1078. 'Stmt_If->else' => $stripLeft,
  1079. 'Stmt_Namespace->name' => $stripLeft,
  1080. 'Stmt_Property->type' => $stripRight,
  1081. 'Stmt_PropertyProperty->default' => $stripEquals,
  1082. 'Stmt_Return->expr' => $stripBoth,
  1083. 'Stmt_StaticVar->default' => $stripEquals,
  1084. 'Stmt_TraitUseAdaptation_Alias->newName' => $stripLeft,
  1085. 'Stmt_TryCatch->finally' => $stripLeft,
  1086. // 'Stmt_Case->cond': Replace with "default"
  1087. // 'Stmt_Class->name': Unclear what to do
  1088. // 'Stmt_Declare->stmts': Not a plain node
  1089. // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a plain node
  1090. ];
  1091. }
  1092. protected function initializeInsertionMap() {
  1093. if ($this->insertionMap) return;
  1094. // TODO: "yield" where both key and value are inserted doesn't work
  1095. $this->insertionMap = [
  1096. 'Expr_ArrayDimFetch->dim' => ['[', false, null, null],
  1097. 'Expr_ArrayItem->key' => [null, false, null, ' => '],
  1098. 'Expr_Closure->returnType' => [')', false, ' : ', null],
  1099. 'Expr_Ternary->if' => ['?', false, ' ', ' '],
  1100. 'Expr_Yield->key' => [\T_YIELD, false, null, ' => '],
  1101. 'Expr_Yield->value' => [\T_YIELD, false, ' ', null],
  1102. 'Param->type' => [null, false, null, ' '],
  1103. 'Param->default' => [null, false, ' = ', null],
  1104. 'Stmt_Break->num' => [\T_BREAK, false, ' ', null],
  1105. 'Stmt_ClassMethod->returnType' => [')', false, ' : ', null],
  1106. 'Stmt_Class->extends' => [null, false, ' extends ', null],
  1107. 'Expr_PrintableNewAnonClass->extends' => [null, ' extends ', null],
  1108. 'Stmt_Continue->num' => [\T_CONTINUE, false, ' ', null],
  1109. 'Stmt_Foreach->keyVar' => [\T_AS, false, null, ' => '],
  1110. 'Stmt_Function->returnType' => [')', false, ' : ', null],
  1111. 'Stmt_If->else' => [null, false, ' ', null],
  1112. 'Stmt_Namespace->name' => [\T_NAMESPACE, false, ' ', null],
  1113. 'Stmt_Property->type' => [\T_VARIABLE, true, null, ' '],
  1114. 'Stmt_PropertyProperty->default' => [null, false, ' = ', null],
  1115. 'Stmt_Return->expr' => [\T_RETURN, false, ' ', null],
  1116. 'Stmt_StaticVar->default' => [null, false, ' = ', null],
  1117. //'Stmt_TraitUseAdaptation_Alias->newName' => [T_AS, false, ' ', null], // TODO
  1118. 'Stmt_TryCatch->finally' => [null, false, ' ', null],
  1119. // 'Expr_Exit->expr': Complicated due to optional ()
  1120. // 'Stmt_Case->cond': Conversion from default to case
  1121. // 'Stmt_Class->name': Unclear
  1122. // 'Stmt_Declare->stmts': Not a proper node
  1123. // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a proper node
  1124. ];
  1125. }
  1126. protected function initializeListInsertionMap() {
  1127. if ($this->listInsertionMap) return;
  1128. $this->listInsertionMap = [
  1129. // special
  1130. //'Expr_ShellExec->parts' => '', // TODO These need to be treated more carefully
  1131. //'Scalar_Encapsed->parts' => '',
  1132. 'Stmt_Catch->types' => '|',
  1133. 'Stmt_If->elseifs' => ' ',
  1134. 'Stmt_TryCatch->catches' => ' ',
  1135. // comma-separated lists
  1136. 'Expr_Array->items' => ', ',
  1137. 'Expr_Closure->params' => ', ',
  1138. 'Expr_Closure->uses' => ', ',
  1139. 'Expr_FuncCall->args' => ', ',
  1140. 'Expr_Isset->vars' => ', ',
  1141. 'Expr_List->items' => ', ',
  1142. 'Expr_MethodCall->args' => ', ',
  1143. 'Expr_New->args' => ', ',
  1144. 'Expr_PrintableNewAnonClass->args' => ', ',
  1145. 'Expr_StaticCall->args' => ', ',
  1146. 'Stmt_ClassConst->consts' => ', ',
  1147. 'Stmt_ClassMethod->params' => ', ',
  1148. 'Stmt_Class->implements' => ', ',
  1149. 'Expr_PrintableNewAnonClass->implements' => ', ',
  1150. 'Stmt_Const->consts' => ', ',
  1151. 'Stmt_Declare->declares' => ', ',
  1152. 'Stmt_Echo->exprs' => ', ',
  1153. 'Stmt_For->init' => ', ',
  1154. 'Stmt_For->cond' => ', ',
  1155. 'Stmt_For->loop' => ', ',
  1156. 'Stmt_Function->params' => ', ',
  1157. 'Stmt_Global->vars' => ', ',
  1158. 'Stmt_GroupUse->uses' => ', ',
  1159. 'Stmt_Interface->extends' => ', ',
  1160. 'Stmt_Property->props' => ', ',
  1161. 'Stmt_StaticVar->vars' => ', ',
  1162. 'Stmt_TraitUse->traits' => ', ',
  1163. 'Stmt_TraitUseAdaptation_Precedence->insteadof' => ', ',
  1164. 'Stmt_Unset->vars' => ', ',
  1165. 'Stmt_Use->uses' => ', ',
  1166. // statement lists
  1167. 'Expr_Closure->stmts' => "\n",
  1168. 'Stmt_Case->stmts' => "\n",
  1169. 'Stmt_Catch->stmts' => "\n",
  1170. 'Stmt_Class->stmts' => "\n",
  1171. 'Expr_PrintableNewAnonClass->stmts' => "\n",
  1172. 'Stmt_Interface->stmts' => "\n",
  1173. 'Stmt_Trait->stmts' => "\n",
  1174. 'Stmt_ClassMethod->stmts' => "\n",
  1175. 'Stmt_Declare->stmts' => "\n",
  1176. 'Stmt_Do->stmts' => "\n",
  1177. 'Stmt_ElseIf->stmts' => "\n",
  1178. 'Stmt_Else->stmts' => "\n",
  1179. 'Stmt_Finally->stmts' => "\n",
  1180. 'Stmt_Foreach->stmts' => "\n",
  1181. 'Stmt_For->stmts' => "\n",
  1182. 'Stmt_Function->stmts' => "\n",
  1183. 'Stmt_If->stmts' => "\n",
  1184. 'Stmt_Namespace->stmts' => "\n",
  1185. 'Stmt_Switch->cases' => "\n",
  1186. 'Stmt_TraitUse->adaptations' => "\n",
  1187. 'Stmt_TryCatch->stmts' => "\n",
  1188. 'Stmt_While->stmts' => "\n",
  1189. ];
  1190. }
  1191. protected function initializeModifierChangeMap() {
  1192. if ($this->modifierChangeMap) return;
  1193. $this->modifierChangeMap = [
  1194. 'Stmt_ClassConst->flags' => \T_CONST,
  1195. 'Stmt_ClassMethod->flags' => \T_FUNCTION,
  1196. 'Stmt_Class->flags' => \T_CLASS,
  1197. 'Stmt_Property->flags' => \T_VARIABLE,
  1198. //'Stmt_TraitUseAdaptation_Alias->newModifier' => 0, // TODO
  1199. ];
  1200. // List of integer subnodes that are not modifiers:
  1201. // Expr_Include->type
  1202. // Stmt_GroupUse->type
  1203. // Stmt_Use->type
  1204. // Stmt_UseUse->type
  1205. }
  1206. }