PrettyPrinterAbstract.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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, 0],
  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. $isStmtList = $subNodeName === 'stmts';
  628. $beforeFirstKeepOrReplace = true;
  629. $skipRemovedNode = false;
  630. $delayedAdd = [];
  631. $lastElemIndentLevel = $this->indentLevel;
  632. $insertNewline = false;
  633. if ($insertStr === "\n") {
  634. $insertStr = '';
  635. $insertNewline = true;
  636. }
  637. if ($isStmtList && \count($origNodes) === 1 && \count($nodes) !== 1) {
  638. $startPos = $origNodes[0]->getStartTokenPos();
  639. $endPos = $origNodes[0]->getEndTokenPos();
  640. \assert($startPos >= 0 && $endPos >= 0);
  641. if (!$this->origTokens->haveBraces($startPos, $endPos)) {
  642. // This was a single statement without braces, but either additional statements
  643. // have been added, or the single statement has been removed. This requires the
  644. // addition of braces. For now fall back.
  645. // TODO: Try to preserve formatting
  646. return null;
  647. }
  648. }
  649. $result = '';
  650. foreach ($diff as $i => $diffElem) {
  651. $diffType = $diffElem->type;
  652. /** @var Node|null $arrItem */
  653. $arrItem = $diffElem->new;
  654. /** @var Node|null $origArrItem */
  655. $origArrItem = $diffElem->old;
  656. if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
  657. $beforeFirstKeepOrReplace = false;
  658. if ($origArrItem === null || $arrItem === null) {
  659. // We can only handle the case where both are null
  660. if ($origArrItem === $arrItem) {
  661. continue;
  662. }
  663. return null;
  664. }
  665. if (!$arrItem instanceof Node || !$origArrItem instanceof Node) {
  666. // We can only deal with nodes. This can occur for Names, which use string arrays.
  667. return null;
  668. }
  669. $itemStartPos = $origArrItem->getStartTokenPos();
  670. $itemEndPos = $origArrItem->getEndTokenPos();
  671. \assert($itemStartPos >= 0 && $itemEndPos >= 0 && $itemStartPos >= $pos);
  672. $origIndentLevel = $this->indentLevel;
  673. $lastElemIndentLevel = $this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment;
  674. $this->setIndentLevel($lastElemIndentLevel);
  675. $comments = $arrItem->getComments();
  676. $origComments = $origArrItem->getComments();
  677. $commentStartPos = $origComments ? $origComments[0]->getStartTokenPos() : $itemStartPos;
  678. \assert($commentStartPos >= 0);
  679. if ($commentStartPos < $pos) {
  680. // Comments may be assigned to multiple nodes if they start at the same position.
  681. // Make sure we don't try to print them multiple times.
  682. $commentStartPos = $itemStartPos;
  683. }
  684. if ($skipRemovedNode) {
  685. if ($isStmtList && $this->origTokens->haveBracesInRange($pos, $itemStartPos)) {
  686. // We'd remove the brace of a code block.
  687. // TODO: Preserve formatting.
  688. $this->setIndentLevel($origIndentLevel);
  689. return null;
  690. }
  691. } else {
  692. $result .= $this->origTokens->getTokenCode(
  693. $pos, $commentStartPos, $indentAdjustment);
  694. }
  695. if (!empty($delayedAdd)) {
  696. /** @var Node $delayedAddNode */
  697. foreach ($delayedAdd as $delayedAddNode) {
  698. if ($insertNewline) {
  699. $delayedAddComments = $delayedAddNode->getComments();
  700. if ($delayedAddComments) {
  701. $result .= $this->pComments($delayedAddComments) . $this->nl;
  702. }
  703. }
  704. $this->safeAppend($result, $this->p($delayedAddNode, true));
  705. if ($insertNewline) {
  706. $result .= $insertStr . $this->nl;
  707. } else {
  708. $result .= $insertStr;
  709. }
  710. }
  711. $delayedAdd = [];
  712. }
  713. if ($comments !== $origComments) {
  714. if ($comments) {
  715. $result .= $this->pComments($comments) . $this->nl;
  716. }
  717. } else {
  718. $result .= $this->origTokens->getTokenCode(
  719. $commentStartPos, $itemStartPos, $indentAdjustment);
  720. }
  721. // If we had to remove anything, we have done so now.
  722. $skipRemovedNode = false;
  723. } elseif ($diffType === DiffElem::TYPE_ADD) {
  724. if (null === $insertStr) {
  725. // We don't have insertion information for this list type
  726. return null;
  727. }
  728. if ($insertStr === ', ' && $this->isMultiline($origNodes)) {
  729. $insertStr = ',';
  730. $insertNewline = true;
  731. }
  732. if ($beforeFirstKeepOrReplace) {
  733. // Will be inserted at the next "replace" or "keep" element
  734. $delayedAdd[] = $arrItem;
  735. continue;
  736. }
  737. $itemStartPos = $pos;
  738. $itemEndPos = $pos - 1;
  739. $origIndentLevel = $this->indentLevel;
  740. $this->setIndentLevel($lastElemIndentLevel);
  741. if ($insertNewline) {
  742. $comments = $arrItem->getComments();
  743. if ($comments) {
  744. $result .= $this->nl . $this->pComments($comments);
  745. }
  746. $result .= $insertStr . $this->nl;
  747. } else {
  748. $result .= $insertStr;
  749. }
  750. } elseif ($diffType === DiffElem::TYPE_REMOVE) {
  751. if (!$origArrItem instanceof Node) {
  752. // We only support removal for nodes
  753. return null;
  754. }
  755. $itemStartPos = $origArrItem->getStartTokenPos();
  756. $itemEndPos = $origArrItem->getEndTokenPos();
  757. \assert($itemStartPos >= 0 && $itemEndPos >= 0);
  758. // Consider comments part of the node.
  759. $origComments = $origArrItem->getComments();
  760. if ($origComments) {
  761. $itemStartPos = $origComments[0]->getStartTokenPos();
  762. }
  763. if ($i === 0) {
  764. // If we're removing from the start, keep the tokens before the node and drop those after it,
  765. // instead of the other way around.
  766. $result .= $this->origTokens->getTokenCode(
  767. $pos, $itemStartPos, $indentAdjustment);
  768. $skipRemovedNode = true;
  769. } else {
  770. if ($isStmtList && $this->origTokens->haveBracesInRange($pos, $itemStartPos)) {
  771. // We'd remove the brace of a code block.
  772. // TODO: Preserve formatting.
  773. return null;
  774. }
  775. }
  776. $pos = $itemEndPos + 1;
  777. continue;
  778. } else {
  779. throw new \Exception("Shouldn't happen");
  780. }
  781. if (null !== $fixup && $arrItem->getAttribute('origNode') !== $origArrItem) {
  782. $res = $this->pFixup($fixup, $arrItem, null, $itemStartPos, $itemEndPos);
  783. } else {
  784. $res = $this->p($arrItem, true);
  785. }
  786. $this->safeAppend($result, $res);
  787. $this->setIndentLevel($origIndentLevel);
  788. $pos = $itemEndPos + 1;
  789. }
  790. if ($skipRemovedNode) {
  791. // TODO: Support removing single node.
  792. return null;
  793. }
  794. if (!empty($delayedAdd)) {
  795. if (!isset($this->emptyListInsertionMap[$mapKey])) {
  796. return null;
  797. }
  798. list($findToken, $extraLeft, $extraRight) = $this->emptyListInsertionMap[$mapKey];
  799. if (null !== $findToken) {
  800. $insertPos = $this->origTokens->findRight($pos, $findToken) + 1;
  801. $result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment);
  802. $pos = $insertPos;
  803. }
  804. $first = true;
  805. $result .= $extraLeft;
  806. foreach ($delayedAdd as $delayedAddNode) {
  807. if (!$first) {
  808. $result .= $insertStr;
  809. }
  810. $result .= $this->p($delayedAddNode, true);
  811. $first = false;
  812. }
  813. $result .= $extraRight;
  814. }
  815. return $result;
  816. }
  817. /**
  818. * Print node with fixups.
  819. *
  820. * Fixups here refer to the addition of extra parentheses, braces or other characters, that
  821. * are required to preserve program semantics in a certain context (e.g. to maintain precedence
  822. * or because only certain expressions are allowed in certain places).
  823. *
  824. * @param int $fixup Fixup type
  825. * @param Node $subNode Subnode to print
  826. * @param string|null $parentClass Class of parent node
  827. * @param int $subStartPos Original start pos of subnode
  828. * @param int $subEndPos Original end pos of subnode
  829. *
  830. * @return string Result of fixed-up print of subnode
  831. */
  832. protected function pFixup(int $fixup, Node $subNode, $parentClass, int $subStartPos, int $subEndPos) : string {
  833. switch ($fixup) {
  834. case self::FIXUP_PREC_LEFT:
  835. case self::FIXUP_PREC_RIGHT:
  836. if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) {
  837. list($precedence, $associativity) = $this->precedenceMap[$parentClass];
  838. return $this->pPrec($subNode, $precedence, $associativity,
  839. $fixup === self::FIXUP_PREC_LEFT ? -1 : 1);
  840. }
  841. break;
  842. case self::FIXUP_CALL_LHS:
  843. if ($this->callLhsRequiresParens($subNode)
  844. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  845. ) {
  846. return '(' . $this->p($subNode) . ')';
  847. }
  848. break;
  849. case self::FIXUP_DEREF_LHS:
  850. if ($this->dereferenceLhsRequiresParens($subNode)
  851. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  852. ) {
  853. return '(' . $this->p($subNode) . ')';
  854. }
  855. break;
  856. case self::FIXUP_BRACED_NAME:
  857. case self::FIXUP_VAR_BRACED_NAME:
  858. if ($subNode instanceof Expr
  859. && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
  860. ) {
  861. return ($fixup === self::FIXUP_VAR_BRACED_NAME ? '$' : '')
  862. . '{' . $this->p($subNode) . '}';
  863. }
  864. break;
  865. case self::FIXUP_ENCAPSED:
  866. if (!$subNode instanceof Scalar\EncapsedStringPart
  867. && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
  868. ) {
  869. return '{' . $this->p($subNode) . '}';
  870. }
  871. break;
  872. default:
  873. throw new \Exception('Cannot happen');
  874. }
  875. // Nothing special to do
  876. return $this->p($subNode);
  877. }
  878. /**
  879. * Appends to a string, ensuring whitespace between label characters.
  880. *
  881. * Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x".
  882. * Without safeAppend the result would be "echox", which does not preserve semantics.
  883. *
  884. * @param string $str
  885. * @param string $append
  886. */
  887. protected function safeAppend(string &$str, string $append) {
  888. if ($str === "") {
  889. $str = $append;
  890. return;
  891. }
  892. if ($append === "") {
  893. return;
  894. }
  895. if (!$this->labelCharMap[$append[0]]
  896. || !$this->labelCharMap[$str[\strlen($str) - 1]]) {
  897. $str .= $append;
  898. } else {
  899. $str .= " " . $append;
  900. }
  901. }
  902. /**
  903. * Determines whether the LHS of a call must be wrapped in parenthesis.
  904. *
  905. * @param Node $node LHS of a call
  906. *
  907. * @return bool Whether parentheses are required
  908. */
  909. protected function callLhsRequiresParens(Node $node) : bool {
  910. return !($node instanceof Node\Name
  911. || $node instanceof Expr\Variable
  912. || $node instanceof Expr\ArrayDimFetch
  913. || $node instanceof Expr\FuncCall
  914. || $node instanceof Expr\MethodCall
  915. || $node instanceof Expr\NullsafeMethodCall
  916. || $node instanceof Expr\StaticCall
  917. || $node instanceof Expr\Array_);
  918. }
  919. /**
  920. * Determines whether the LHS of a dereferencing operation must be wrapped in parenthesis.
  921. *
  922. * @param Node $node LHS of dereferencing operation
  923. *
  924. * @return bool Whether parentheses are required
  925. */
  926. protected function dereferenceLhsRequiresParens(Node $node) : bool {
  927. return !($node instanceof Expr\Variable
  928. || $node instanceof Node\Name
  929. || $node instanceof Expr\ArrayDimFetch
  930. || $node instanceof Expr\PropertyFetch
  931. || $node instanceof Expr\NullsafePropertyFetch
  932. || $node instanceof Expr\StaticPropertyFetch
  933. || $node instanceof Expr\FuncCall
  934. || $node instanceof Expr\MethodCall
  935. || $node instanceof Expr\NullsafeMethodCall
  936. || $node instanceof Expr\StaticCall
  937. || $node instanceof Expr\Array_
  938. || $node instanceof Scalar\String_
  939. || $node instanceof Expr\ConstFetch
  940. || $node instanceof Expr\ClassConstFetch);
  941. }
  942. /**
  943. * Print modifiers, including trailing whitespace.
  944. *
  945. * @param int $modifiers Modifier mask to print
  946. *
  947. * @return string Printed modifiers
  948. */
  949. protected function pModifiers(int $modifiers) {
  950. return ($modifiers & Stmt\Class_::MODIFIER_PUBLIC ? 'public ' : '')
  951. . ($modifiers & Stmt\Class_::MODIFIER_PROTECTED ? 'protected ' : '')
  952. . ($modifiers & Stmt\Class_::MODIFIER_PRIVATE ? 'private ' : '')
  953. . ($modifiers & Stmt\Class_::MODIFIER_STATIC ? 'static ' : '')
  954. . ($modifiers & Stmt\Class_::MODIFIER_ABSTRACT ? 'abstract ' : '')
  955. . ($modifiers & Stmt\Class_::MODIFIER_FINAL ? 'final ' : '');
  956. }
  957. /**
  958. * Determine whether a list of nodes uses multiline formatting.
  959. *
  960. * @param (Node|null)[] $nodes Node list
  961. *
  962. * @return bool Whether multiline formatting is used
  963. */
  964. protected function isMultiline(array $nodes) : bool {
  965. if (\count($nodes) < 2) {
  966. return false;
  967. }
  968. $pos = -1;
  969. foreach ($nodes as $node) {
  970. if (null === $node) {
  971. continue;
  972. }
  973. $endPos = $node->getEndTokenPos() + 1;
  974. if ($pos >= 0) {
  975. $text = $this->origTokens->getTokenCode($pos, $endPos, 0);
  976. if (false === strpos($text, "\n")) {
  977. // We require that a newline is present between *every* item. If the formatting
  978. // is inconsistent, with only some items having newlines, we don't consider it
  979. // as multiline
  980. return false;
  981. }
  982. }
  983. $pos = $endPos;
  984. }
  985. return true;
  986. }
  987. /**
  988. * Lazily initializes label char map.
  989. *
  990. * The label char map determines whether a certain character may occur in a label.
  991. */
  992. protected function initializeLabelCharMap() {
  993. if ($this->labelCharMap) return;
  994. $this->labelCharMap = [];
  995. for ($i = 0; $i < 256; $i++) {
  996. // Since PHP 7.1 The lower range is 0x80. However, we also want to support code for
  997. // older versions.
  998. $this->labelCharMap[chr($i)] = $i >= 0x7f || ctype_alnum($i);
  999. }
  1000. }
  1001. /**
  1002. * Lazily initializes node list differ.
  1003. *
  1004. * The node list differ is used to determine differences between two array subnodes.
  1005. */
  1006. protected function initializeNodeListDiffer() {
  1007. if ($this->nodeListDiffer) return;
  1008. $this->nodeListDiffer = new Internal\Differ(function ($a, $b) {
  1009. if ($a instanceof Node && $b instanceof Node) {
  1010. return $a === $b->getAttribute('origNode');
  1011. }
  1012. // Can happen for array destructuring
  1013. return $a === null && $b === null;
  1014. });
  1015. }
  1016. /**
  1017. * Lazily initializes fixup map.
  1018. *
  1019. * The fixup map is used to determine whether a certain subnode of a certain node may require
  1020. * some kind of "fixup" operation, e.g. the addition of parenthesis or braces.
  1021. */
  1022. protected function initializeFixupMap() {
  1023. if ($this->fixupMap) return;
  1024. $this->fixupMap = [
  1025. Expr\PreInc::class => ['var' => self::FIXUP_PREC_RIGHT],
  1026. Expr\PreDec::class => ['var' => self::FIXUP_PREC_RIGHT],
  1027. Expr\PostInc::class => ['var' => self::FIXUP_PREC_LEFT],
  1028. Expr\PostDec::class => ['var' => self::FIXUP_PREC_LEFT],
  1029. Expr\Instanceof_::class => [
  1030. 'expr' => self::FIXUP_PREC_LEFT,
  1031. 'class' => self::FIXUP_PREC_RIGHT, // TODO: FIXUP_NEW_VARIABLE
  1032. ],
  1033. Expr\Ternary::class => [
  1034. 'cond' => self::FIXUP_PREC_LEFT,
  1035. 'else' => self::FIXUP_PREC_RIGHT,
  1036. ],
  1037. Expr\FuncCall::class => ['name' => self::FIXUP_CALL_LHS],
  1038. Expr\StaticCall::class => ['class' => self::FIXUP_DEREF_LHS],
  1039. Expr\ArrayDimFetch::class => ['var' => self::FIXUP_DEREF_LHS],
  1040. Expr\ClassConstFetch::class => ['var' => self::FIXUP_DEREF_LHS],
  1041. Expr\New_::class => ['class' => self::FIXUP_DEREF_LHS], // TODO: FIXUP_NEW_VARIABLE
  1042. Expr\MethodCall::class => [
  1043. 'var' => self::FIXUP_DEREF_LHS,
  1044. 'name' => self::FIXUP_BRACED_NAME,
  1045. ],
  1046. Expr\NullsafeMethodCall::class => [
  1047. 'var' => self::FIXUP_DEREF_LHS,
  1048. 'name' => self::FIXUP_BRACED_NAME,
  1049. ],
  1050. Expr\StaticPropertyFetch::class => [
  1051. 'class' => self::FIXUP_DEREF_LHS,
  1052. 'name' => self::FIXUP_VAR_BRACED_NAME,
  1053. ],
  1054. Expr\PropertyFetch::class => [
  1055. 'var' => self::FIXUP_DEREF_LHS,
  1056. 'name' => self::FIXUP_BRACED_NAME,
  1057. ],
  1058. Expr\NullsafePropertyFetch::class => [
  1059. 'var' => self::FIXUP_DEREF_LHS,
  1060. 'name' => self::FIXUP_BRACED_NAME,
  1061. ],
  1062. Scalar\Encapsed::class => [
  1063. 'parts' => self::FIXUP_ENCAPSED,
  1064. ],
  1065. ];
  1066. $binaryOps = [
  1067. BinaryOp\Pow::class, BinaryOp\Mul::class, BinaryOp\Div::class, BinaryOp\Mod::class,
  1068. BinaryOp\Plus::class, BinaryOp\Minus::class, BinaryOp\Concat::class,
  1069. BinaryOp\ShiftLeft::class, BinaryOp\ShiftRight::class, BinaryOp\Smaller::class,
  1070. BinaryOp\SmallerOrEqual::class, BinaryOp\Greater::class, BinaryOp\GreaterOrEqual::class,
  1071. BinaryOp\Equal::class, BinaryOp\NotEqual::class, BinaryOp\Identical::class,
  1072. BinaryOp\NotIdentical::class, BinaryOp\Spaceship::class, BinaryOp\BitwiseAnd::class,
  1073. BinaryOp\BitwiseXor::class, BinaryOp\BitwiseOr::class, BinaryOp\BooleanAnd::class,
  1074. BinaryOp\BooleanOr::class, BinaryOp\Coalesce::class, BinaryOp\LogicalAnd::class,
  1075. BinaryOp\LogicalXor::class, BinaryOp\LogicalOr::class,
  1076. ];
  1077. foreach ($binaryOps as $binaryOp) {
  1078. $this->fixupMap[$binaryOp] = [
  1079. 'left' => self::FIXUP_PREC_LEFT,
  1080. 'right' => self::FIXUP_PREC_RIGHT
  1081. ];
  1082. }
  1083. $assignOps = [
  1084. Expr\Assign::class, Expr\AssignRef::class, AssignOp\Plus::class, AssignOp\Minus::class,
  1085. AssignOp\Mul::class, AssignOp\Div::class, AssignOp\Concat::class, AssignOp\Mod::class,
  1086. AssignOp\BitwiseAnd::class, AssignOp\BitwiseOr::class, AssignOp\BitwiseXor::class,
  1087. AssignOp\ShiftLeft::class, AssignOp\ShiftRight::class, AssignOp\Pow::class, AssignOp\Coalesce::class
  1088. ];
  1089. foreach ($assignOps as $assignOp) {
  1090. $this->fixupMap[$assignOp] = [
  1091. 'var' => self::FIXUP_PREC_LEFT,
  1092. 'expr' => self::FIXUP_PREC_RIGHT,
  1093. ];
  1094. }
  1095. $prefixOps = [
  1096. Expr\BitwiseNot::class, Expr\BooleanNot::class, Expr\UnaryPlus::class, Expr\UnaryMinus::class,
  1097. Cast\Int_::class, Cast\Double::class, Cast\String_::class, Cast\Array_::class,
  1098. Cast\Object_::class, Cast\Bool_::class, Cast\Unset_::class, Expr\ErrorSuppress::class,
  1099. Expr\YieldFrom::class, Expr\Print_::class, Expr\Include_::class,
  1100. ];
  1101. foreach ($prefixOps as $prefixOp) {
  1102. $this->fixupMap[$prefixOp] = ['expr' => self::FIXUP_PREC_RIGHT];
  1103. }
  1104. }
  1105. /**
  1106. * Lazily initializes the removal map.
  1107. *
  1108. * The removal map is used to determine which additional tokens should be returned when a
  1109. * certain node is replaced by null.
  1110. */
  1111. protected function initializeRemovalMap() {
  1112. if ($this->removalMap) return;
  1113. $stripBoth = ['left' => \T_WHITESPACE, 'right' => \T_WHITESPACE];
  1114. $stripLeft = ['left' => \T_WHITESPACE];
  1115. $stripRight = ['right' => \T_WHITESPACE];
  1116. $stripDoubleArrow = ['right' => \T_DOUBLE_ARROW];
  1117. $stripColon = ['left' => ':'];
  1118. $stripEquals = ['left' => '='];
  1119. $this->removalMap = [
  1120. 'Expr_ArrayDimFetch->dim' => $stripBoth,
  1121. 'Expr_ArrayItem->key' => $stripDoubleArrow,
  1122. 'Expr_ArrowFunction->returnType' => $stripColon,
  1123. 'Expr_Closure->returnType' => $stripColon,
  1124. 'Expr_Exit->expr' => $stripBoth,
  1125. 'Expr_Ternary->if' => $stripBoth,
  1126. 'Expr_Yield->key' => $stripDoubleArrow,
  1127. 'Expr_Yield->value' => $stripBoth,
  1128. 'Param->type' => $stripRight,
  1129. 'Param->default' => $stripEquals,
  1130. 'Stmt_Break->num' => $stripBoth,
  1131. 'Stmt_Catch->var' => $stripLeft,
  1132. 'Stmt_ClassMethod->returnType' => $stripColon,
  1133. 'Stmt_Class->extends' => ['left' => \T_EXTENDS],
  1134. 'Expr_PrintableNewAnonClass->extends' => ['left' => \T_EXTENDS],
  1135. 'Stmt_Continue->num' => $stripBoth,
  1136. 'Stmt_Foreach->keyVar' => $stripDoubleArrow,
  1137. 'Stmt_Function->returnType' => $stripColon,
  1138. 'Stmt_If->else' => $stripLeft,
  1139. 'Stmt_Namespace->name' => $stripLeft,
  1140. 'Stmt_Property->type' => $stripRight,
  1141. 'Stmt_PropertyProperty->default' => $stripEquals,
  1142. 'Stmt_Return->expr' => $stripBoth,
  1143. 'Stmt_StaticVar->default' => $stripEquals,
  1144. 'Stmt_TraitUseAdaptation_Alias->newName' => $stripLeft,
  1145. 'Stmt_TryCatch->finally' => $stripLeft,
  1146. // 'Stmt_Case->cond': Replace with "default"
  1147. // 'Stmt_Class->name': Unclear what to do
  1148. // 'Stmt_Declare->stmts': Not a plain node
  1149. // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a plain node
  1150. ];
  1151. }
  1152. protected function initializeInsertionMap() {
  1153. if ($this->insertionMap) return;
  1154. // TODO: "yield" where both key and value are inserted doesn't work
  1155. // [$find, $beforeToken, $extraLeft, $extraRight]
  1156. $this->insertionMap = [
  1157. 'Expr_ArrayDimFetch->dim' => ['[', false, null, null],
  1158. 'Expr_ArrayItem->key' => [null, false, null, ' => '],
  1159. 'Expr_ArrowFunction->returnType' => [')', false, ' : ', null],
  1160. 'Expr_Closure->returnType' => [')', false, ' : ', null],
  1161. 'Expr_Ternary->if' => ['?', false, ' ', ' '],
  1162. 'Expr_Yield->key' => [\T_YIELD, false, null, ' => '],
  1163. 'Expr_Yield->value' => [\T_YIELD, false, ' ', null],
  1164. 'Param->type' => [null, false, null, ' '],
  1165. 'Param->default' => [null, false, ' = ', null],
  1166. 'Stmt_Break->num' => [\T_BREAK, false, ' ', null],
  1167. 'Stmt_Catch->var' => [null, false, ' ', null],
  1168. 'Stmt_ClassMethod->returnType' => [')', false, ' : ', null],
  1169. 'Stmt_Class->extends' => [null, false, ' extends ', null],
  1170. 'Expr_PrintableNewAnonClass->extends' => [null, ' extends ', null],
  1171. 'Stmt_Continue->num' => [\T_CONTINUE, false, ' ', null],
  1172. 'Stmt_Foreach->keyVar' => [\T_AS, false, null, ' => '],
  1173. 'Stmt_Function->returnType' => [')', false, ' : ', null],
  1174. 'Stmt_If->else' => [null, false, ' ', null],
  1175. 'Stmt_Namespace->name' => [\T_NAMESPACE, false, ' ', null],
  1176. 'Stmt_Property->type' => [\T_VARIABLE, true, null, ' '],
  1177. 'Stmt_PropertyProperty->default' => [null, false, ' = ', null],
  1178. 'Stmt_Return->expr' => [\T_RETURN, false, ' ', null],
  1179. 'Stmt_StaticVar->default' => [null, false, ' = ', null],
  1180. //'Stmt_TraitUseAdaptation_Alias->newName' => [T_AS, false, ' ', null], // TODO
  1181. 'Stmt_TryCatch->finally' => [null, false, ' ', null],
  1182. // 'Expr_Exit->expr': Complicated due to optional ()
  1183. // 'Stmt_Case->cond': Conversion from default to case
  1184. // 'Stmt_Class->name': Unclear
  1185. // 'Stmt_Declare->stmts': Not a proper node
  1186. // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a proper node
  1187. ];
  1188. }
  1189. protected function initializeListInsertionMap() {
  1190. if ($this->listInsertionMap) return;
  1191. $this->listInsertionMap = [
  1192. // special
  1193. //'Expr_ShellExec->parts' => '', // TODO These need to be treated more carefully
  1194. //'Scalar_Encapsed->parts' => '',
  1195. 'Stmt_Catch->types' => '|',
  1196. 'UnionType->types' => '|',
  1197. 'Stmt_If->elseifs' => ' ',
  1198. 'Stmt_TryCatch->catches' => ' ',
  1199. // comma-separated lists
  1200. 'Expr_Array->items' => ', ',
  1201. 'Expr_ArrowFunction->params' => ', ',
  1202. 'Expr_Closure->params' => ', ',
  1203. 'Expr_Closure->uses' => ', ',
  1204. 'Expr_FuncCall->args' => ', ',
  1205. 'Expr_Isset->vars' => ', ',
  1206. 'Expr_List->items' => ', ',
  1207. 'Expr_MethodCall->args' => ', ',
  1208. 'Expr_NullsafeMethodCall->args' => ', ',
  1209. 'Expr_New->args' => ', ',
  1210. 'Expr_PrintableNewAnonClass->args' => ', ',
  1211. 'Expr_StaticCall->args' => ', ',
  1212. 'Stmt_ClassConst->consts' => ', ',
  1213. 'Stmt_ClassMethod->params' => ', ',
  1214. 'Stmt_Class->implements' => ', ',
  1215. 'Expr_PrintableNewAnonClass->implements' => ', ',
  1216. 'Stmt_Const->consts' => ', ',
  1217. 'Stmt_Declare->declares' => ', ',
  1218. 'Stmt_Echo->exprs' => ', ',
  1219. 'Stmt_For->init' => ', ',
  1220. 'Stmt_For->cond' => ', ',
  1221. 'Stmt_For->loop' => ', ',
  1222. 'Stmt_Function->params' => ', ',
  1223. 'Stmt_Global->vars' => ', ',
  1224. 'Stmt_GroupUse->uses' => ', ',
  1225. 'Stmt_Interface->extends' => ', ',
  1226. 'Stmt_Match->arms' => ', ',
  1227. 'Stmt_Property->props' => ', ',
  1228. 'Stmt_StaticVar->vars' => ', ',
  1229. 'Stmt_TraitUse->traits' => ', ',
  1230. 'Stmt_TraitUseAdaptation_Precedence->insteadof' => ', ',
  1231. 'Stmt_Unset->vars' => ', ',
  1232. 'Stmt_Use->uses' => ', ',
  1233. 'MatchArm->conds' => ', ',
  1234. 'AttributeGroup->attrs' => ', ',
  1235. // statement lists
  1236. 'Expr_Closure->stmts' => "\n",
  1237. 'Stmt_Case->stmts' => "\n",
  1238. 'Stmt_Catch->stmts' => "\n",
  1239. 'Stmt_Class->stmts' => "\n",
  1240. 'Expr_PrintableNewAnonClass->stmts' => "\n",
  1241. 'Stmt_Interface->stmts' => "\n",
  1242. 'Stmt_Trait->stmts' => "\n",
  1243. 'Stmt_ClassMethod->stmts' => "\n",
  1244. 'Stmt_Declare->stmts' => "\n",
  1245. 'Stmt_Do->stmts' => "\n",
  1246. 'Stmt_ElseIf->stmts' => "\n",
  1247. 'Stmt_Else->stmts' => "\n",
  1248. 'Stmt_Finally->stmts' => "\n",
  1249. 'Stmt_Foreach->stmts' => "\n",
  1250. 'Stmt_For->stmts' => "\n",
  1251. 'Stmt_Function->stmts' => "\n",
  1252. 'Stmt_If->stmts' => "\n",
  1253. 'Stmt_Namespace->stmts' => "\n",
  1254. 'Stmt_Class->attrGroups' => "\n",
  1255. 'Stmt_Interface->attrGroups' => "\n",
  1256. 'Stmt_Trait->attrGroups' => "\n",
  1257. 'Stmt_Function->attrGroups' => "\n",
  1258. 'Stmt_ClassMethod->attrGroups' => "\n",
  1259. 'Stmt_ClassConst->attrGroups' => "\n",
  1260. 'Stmt_Property->attrGroups' => "\n",
  1261. 'Expr_PrintableNewAnonClass->attrGroups' => ' ',
  1262. 'Expr_Closure->attrGroups' => ' ',
  1263. 'Expr_ArrowFunction->attrGroups' => ' ',
  1264. 'Param->attrGroups' => ' ',
  1265. 'Stmt_Switch->cases' => "\n",
  1266. 'Stmt_TraitUse->adaptations' => "\n",
  1267. 'Stmt_TryCatch->stmts' => "\n",
  1268. 'Stmt_While->stmts' => "\n",
  1269. // dummy for top-level context
  1270. 'File->stmts' => "\n",
  1271. ];
  1272. }
  1273. protected function initializeEmptyListInsertionMap() {
  1274. if ($this->emptyListInsertionMap) return;
  1275. // TODO Insertion into empty statement lists.
  1276. // [$find, $extraLeft, $extraRight]
  1277. $this->emptyListInsertionMap = [
  1278. 'Expr_ArrowFunction->params' => ['(', '', ''],
  1279. 'Expr_Closure->uses' => [')', ' use(', ')'],
  1280. 'Expr_Closure->params' => ['(', '', ''],
  1281. 'Expr_FuncCall->args' => ['(', '', ''],
  1282. 'Expr_MethodCall->args' => ['(', '', ''],
  1283. 'Expr_NullsafeMethodCall->args' => ['(', '', ''],
  1284. 'Expr_New->args' => ['(', '', ''],
  1285. 'Expr_PrintableNewAnonClass->args' => ['(', '', ''],
  1286. 'Expr_PrintableNewAnonClass->implements' => [null, ' implements ', ''],
  1287. 'Expr_StaticCall->args' => ['(', '', ''],
  1288. 'Stmt_Class->implements' => [null, ' implements ', ''],
  1289. 'Stmt_ClassMethod->params' => ['(', '', ''],
  1290. 'Stmt_Interface->extends' => [null, ' extends ', ''],
  1291. 'Stmt_Function->params' => ['(', '', ''],
  1292. /* These cannot be empty to start with:
  1293. * Expr_Isset->vars
  1294. * Stmt_Catch->types
  1295. * Stmt_Const->consts
  1296. * Stmt_ClassConst->consts
  1297. * Stmt_Declare->declares
  1298. * Stmt_Echo->exprs
  1299. * Stmt_Global->vars
  1300. * Stmt_GroupUse->uses
  1301. * Stmt_Property->props
  1302. * Stmt_StaticVar->vars
  1303. * Stmt_TraitUse->traits
  1304. * Stmt_TraitUseAdaptation_Precedence->insteadof
  1305. * Stmt_Unset->vars
  1306. * Stmt_Use->uses
  1307. * UnionType->types
  1308. */
  1309. /* TODO
  1310. * Stmt_If->elseifs
  1311. * Stmt_TryCatch->catches
  1312. * Expr_Array->items
  1313. * Expr_List->items
  1314. * Stmt_For->init
  1315. * Stmt_For->cond
  1316. * Stmt_For->loop
  1317. */
  1318. ];
  1319. }
  1320. protected function initializeModifierChangeMap() {
  1321. if ($this->modifierChangeMap) return;
  1322. $this->modifierChangeMap = [
  1323. 'Stmt_ClassConst->flags' => \T_CONST,
  1324. 'Stmt_ClassMethod->flags' => \T_FUNCTION,
  1325. 'Stmt_Class->flags' => \T_CLASS,
  1326. 'Stmt_Property->flags' => \T_VARIABLE,
  1327. 'Param->flags' => \T_VARIABLE,
  1328. //'Stmt_TraitUseAdaptation_Alias->newModifier' => 0, // TODO
  1329. ];
  1330. // List of integer subnodes that are not modifiers:
  1331. // Expr_Include->type
  1332. // Stmt_GroupUse->type
  1333. // Stmt_Use->type
  1334. // Stmt_UseUse->type
  1335. }
  1336. }