Ingen beskrivning

PrettyPrinterAbstract.php 59KB

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