PrettyPrinterAbstract.php 56 KB

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