PrettyPrinterAbstract.php 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. <?php declare(strict_types=1);
  2. namespace PhpParser;
  3. use PhpParser\Internal\DiffElem;
  4. use PhpParser\Internal\Differ;
  5. use PhpParser\Internal\PrintableNewAnonClassNode;
  6. use PhpParser\Internal\TokenStream;
  7. use PhpParser\Node\AttributeGroup;
  8. use PhpParser\Node\Expr;
  9. use PhpParser\Node\Expr\AssignOp;
  10. use PhpParser\Node\Expr\BinaryOp;
  11. use PhpParser\Node\Expr\Cast;
  12. use PhpParser\Node\IntersectionType;
  13. use PhpParser\Node\MatchArm;
  14. use PhpParser\Node\Param;
  15. use PhpParser\Node\PropertyHook;
  16. use PhpParser\Node\Scalar;
  17. use PhpParser\Node\Stmt;
  18. use PhpParser\Node\UnionType;
  19. abstract class PrettyPrinterAbstract implements PrettyPrinter {
  20. protected const FIXUP_PREC_LEFT = 0; // LHS operand affected by precedence
  21. protected const FIXUP_PREC_RIGHT = 1; // RHS operand affected by precedence
  22. protected const FIXUP_PREC_UNARY = 2; // Only operand affected by precedence
  23. protected const FIXUP_CALL_LHS = 3; // LHS of call
  24. protected const FIXUP_DEREF_LHS = 4; // LHS of dereferencing operation
  25. protected const FIXUP_STATIC_DEREF_LHS = 5; // LHS of static dereferencing operation
  26. protected const FIXUP_BRACED_NAME = 6; // Name operand that may require bracing
  27. protected const FIXUP_VAR_BRACED_NAME = 7; // Name operand that may require ${} bracing
  28. protected const FIXUP_ENCAPSED = 8; // Encapsed string part
  29. protected const FIXUP_NEW = 9; // New/instanceof operand
  30. protected const MAX_PRECEDENCE = 1000;
  31. /** @var array<class-string, array{int, int, int}> */
  32. protected array $precedenceMap = [
  33. // [precedence, precedenceLHS, precedenceRHS]
  34. // Where the latter two are the precedences to use for the LHS and RHS of a binary operator,
  35. // where 1 is added to one of the sides depending on associativity. This information is not
  36. // used for unary operators and set to -1.
  37. Expr\Clone_::class => [-10, 0, 1],
  38. BinaryOp\Pow::class => [ 0, 0, 1],
  39. Expr\BitwiseNot::class => [ 10, -1, -1],
  40. Expr\UnaryPlus::class => [ 10, -1, -1],
  41. Expr\UnaryMinus::class => [ 10, -1, -1],
  42. Cast\Int_::class => [ 10, -1, -1],
  43. Cast\Double::class => [ 10, -1, -1],
  44. Cast\String_::class => [ 10, -1, -1],
  45. Cast\Array_::class => [ 10, -1, -1],
  46. Cast\Object_::class => [ 10, -1, -1],
  47. Cast\Bool_::class => [ 10, -1, -1],
  48. Cast\Unset_::class => [ 10, -1, -1],
  49. Expr\ErrorSuppress::class => [ 10, -1, -1],
  50. Expr\Instanceof_::class => [ 20, -1, -1],
  51. Expr\BooleanNot::class => [ 30, -1, -1],
  52. BinaryOp\Mul::class => [ 40, 41, 40],
  53. BinaryOp\Div::class => [ 40, 41, 40],
  54. BinaryOp\Mod::class => [ 40, 41, 40],
  55. BinaryOp\Plus::class => [ 50, 51, 50],
  56. BinaryOp\Minus::class => [ 50, 51, 50],
  57. BinaryOp\Concat::class => [ 50, 51, 50],
  58. BinaryOp\ShiftLeft::class => [ 60, 61, 60],
  59. BinaryOp\ShiftRight::class => [ 60, 61, 60],
  60. BinaryOp\Smaller::class => [ 70, 70, 70],
  61. BinaryOp\SmallerOrEqual::class => [ 70, 70, 70],
  62. BinaryOp\Greater::class => [ 70, 70, 70],
  63. BinaryOp\GreaterOrEqual::class => [ 70, 70, 70],
  64. BinaryOp\Equal::class => [ 80, 80, 80],
  65. BinaryOp\NotEqual::class => [ 80, 80, 80],
  66. BinaryOp\Identical::class => [ 80, 80, 80],
  67. BinaryOp\NotIdentical::class => [ 80, 80, 80],
  68. BinaryOp\Spaceship::class => [ 80, 80, 80],
  69. BinaryOp\BitwiseAnd::class => [ 90, 91, 90],
  70. BinaryOp\BitwiseXor::class => [100, 101, 100],
  71. BinaryOp\BitwiseOr::class => [110, 111, 110],
  72. BinaryOp\BooleanAnd::class => [120, 121, 120],
  73. BinaryOp\BooleanOr::class => [130, 131, 130],
  74. BinaryOp\Coalesce::class => [140, 140, 141],
  75. Expr\Ternary::class => [150, 150, 150],
  76. Expr\Assign::class => [160, -1, -1],
  77. Expr\AssignRef::class => [160, -1, -1],
  78. AssignOp\Plus::class => [160, -1, -1],
  79. AssignOp\Minus::class => [160, -1, -1],
  80. AssignOp\Mul::class => [160, -1, -1],
  81. AssignOp\Div::class => [160, -1, -1],
  82. AssignOp\Concat::class => [160, -1, -1],
  83. AssignOp\Mod::class => [160, -1, -1],
  84. AssignOp\BitwiseAnd::class => [160, -1, -1],
  85. AssignOp\BitwiseOr::class => [160, -1, -1],
  86. AssignOp\BitwiseXor::class => [160, -1, -1],
  87. AssignOp\ShiftLeft::class => [160, -1, -1],
  88. AssignOp\ShiftRight::class => [160, -1, -1],
  89. AssignOp\Pow::class => [160, -1, -1],
  90. AssignOp\Coalesce::class => [160, -1, -1],
  91. Expr\YieldFrom::class => [170, -1, -1],
  92. Expr\Yield_::class => [175, -1, -1],
  93. Expr\Print_::class => [180, -1, -1],
  94. BinaryOp\LogicalAnd::class => [190, 191, 190],
  95. BinaryOp\LogicalXor::class => [200, 201, 200],
  96. BinaryOp\LogicalOr::class => [210, 211, 210],
  97. Expr\Include_::class => [220, -1, -1],
  98. Expr\ArrowFunction::class => [230, -1, -1],
  99. Expr\Throw_::class => [240, -1, -1],
  100. ];
  101. /** @var int Current indentation level. */
  102. protected int $indentLevel;
  103. /** @var string String for single level of indentation */
  104. private string $indent;
  105. /** @var int Width in spaces to indent by. */
  106. private int $indentWidth;
  107. /** @var bool Whether to use tab indentation. */
  108. private bool $useTabs;
  109. /** @var int Width in spaces of one tab. */
  110. private int $tabWidth = 4;
  111. /** @var string Newline style. Does not include current indentation. */
  112. protected string $newline;
  113. /** @var string Newline including current indentation. */
  114. protected string $nl;
  115. /** @var string|null Token placed at end of doc string to ensure it is followed by a newline.
  116. * Null if flexible doc strings are used. */
  117. protected ?string $docStringEndToken;
  118. /** @var bool Whether semicolon namespaces can be used (i.e. no global namespace is used) */
  119. protected bool $canUseSemicolonNamespaces;
  120. /** @var bool Whether to use short array syntax if the node specifies no preference */
  121. protected bool $shortArraySyntax;
  122. /** @var PhpVersion PHP version to target */
  123. protected PhpVersion $phpVersion;
  124. /** @var TokenStream|null Original tokens for use in format-preserving pretty print */
  125. protected ?TokenStream $origTokens;
  126. /** @var Internal\Differ<Node> Differ for node lists */
  127. protected Differ $nodeListDiffer;
  128. /** @var array<string, bool> Map determining whether a certain character is a label character */
  129. protected array $labelCharMap;
  130. /**
  131. * @var array<string, array<string, int>> Map from token classes and subnode names to FIXUP_* constants.
  132. * This is used during format-preserving prints to place additional parens/braces if necessary.
  133. */
  134. protected array $fixupMap;
  135. /**
  136. * @var array<string, array{left?: int|string, right?: int|string}> Map from "{$node->getType()}->{$subNode}"
  137. * to ['left' => $l, 'right' => $r], where $l and $r specify the token type that needs to be stripped
  138. * when removing this node.
  139. */
  140. protected array $removalMap;
  141. /**
  142. * @var array<string, array{int|string|null, bool, string|null, string|null}> Map from
  143. * "{$node->getType()}->{$subNode}" to [$find, $beforeToken, $extraLeft, $extraRight].
  144. * $find is an optional token after which the insertion occurs. $extraLeft/Right
  145. * are optionally added before/after the main insertions.
  146. */
  147. protected array $insertionMap;
  148. /**
  149. * @var array<string, string> Map From "{$class}->{$subNode}" to string that should be inserted
  150. * between elements of this list subnode.
  151. */
  152. protected array $listInsertionMap;
  153. /**
  154. * @var array<string, array{int|string|null, string, string}>
  155. */
  156. protected array $emptyListInsertionMap;
  157. /** @var array<string, array{string, int}> Map from "{$class}->{$subNode}" to [$printFn, $token]
  158. * where $printFn is the function to print the modifiers and $token is the token before which
  159. * the modifiers should be reprinted. */
  160. protected array $modifierChangeMap;
  161. /**
  162. * Creates a pretty printer instance using the given options.
  163. *
  164. * Supported options:
  165. * * PhpVersion $phpVersion: The PHP version to target (default to PHP 7.4). This option
  166. * controls compatibility of the generated code with older PHP
  167. * versions in cases where a simple stylistic choice exists (e.g.
  168. * array() vs []). It is safe to pretty-print an AST for a newer
  169. * PHP version while specifying an older target (but the result will
  170. * of course not be compatible with the older version in that case).
  171. * * string $newline: The newline style to use. Should be "\n" (default) or "\r\n".
  172. * * string $indent: The indentation to use. Should either be all spaces or a single
  173. * tab. Defaults to four spaces (" ").
  174. * * bool $shortArraySyntax: Whether to use [] instead of array() as the default array
  175. * syntax, if the node does not specify a format. Defaults to whether
  176. * the phpVersion support short array syntax.
  177. *
  178. * @param array{
  179. * phpVersion?: PhpVersion, newline?: string, indent?: string, shortArraySyntax?: bool
  180. * } $options Dictionary of formatting options
  181. */
  182. public function __construct(array $options = []) {
  183. $this->phpVersion = $options['phpVersion'] ?? PhpVersion::fromComponents(7, 4);
  184. $this->newline = $options['newline'] ?? "\n";
  185. if ($this->newline !== "\n" && $this->newline != "\r\n") {
  186. throw new \LogicException('Option "newline" must be one of "\n" or "\r\n"');
  187. }
  188. $this->shortArraySyntax =
  189. $options['shortArraySyntax'] ?? $this->phpVersion->supportsShortArraySyntax();
  190. $this->docStringEndToken =
  191. $this->phpVersion->supportsFlexibleHeredoc() ? null : '_DOC_STRING_END_' . mt_rand();
  192. $this->indent = $indent = $options['indent'] ?? ' ';
  193. if ($indent === "\t") {
  194. $this->useTabs = true;
  195. $this->indentWidth = $this->tabWidth;
  196. } elseif ($indent === \str_repeat(' ', \strlen($indent))) {
  197. $this->useTabs = false;
  198. $this->indentWidth = \strlen($indent);
  199. } else {
  200. throw new \LogicException('Option "indent" must either be all spaces or a single tab');
  201. }
  202. }
  203. /**
  204. * Reset pretty printing state.
  205. */
  206. protected function resetState(): void {
  207. $this->indentLevel = 0;
  208. $this->nl = $this->newline;
  209. $this->origTokens = null;
  210. }
  211. /**
  212. * Set indentation level
  213. *
  214. * @param int $level Level in number of spaces
  215. */
  216. protected function setIndentLevel(int $level): void {
  217. $this->indentLevel = $level;
  218. if ($this->useTabs) {
  219. $tabs = \intdiv($level, $this->tabWidth);
  220. $spaces = $level % $this->tabWidth;
  221. $this->nl = $this->newline . \str_repeat("\t", $tabs) . \str_repeat(' ', $spaces);
  222. } else {
  223. $this->nl = $this->newline . \str_repeat(' ', $level);
  224. }
  225. }
  226. /**
  227. * Increase indentation level.
  228. */
  229. protected function indent(): void {
  230. $this->indentLevel += $this->indentWidth;
  231. $this->nl .= $this->indent;
  232. }
  233. /**
  234. * Decrease indentation level.
  235. */
  236. protected function outdent(): void {
  237. assert($this->indentLevel >= $this->indentWidth);
  238. $this->setIndentLevel($this->indentLevel - $this->indentWidth);
  239. }
  240. /**
  241. * Pretty prints an array of statements.
  242. *
  243. * @param Node[] $stmts Array of statements
  244. *
  245. * @return string Pretty printed statements
  246. */
  247. public function prettyPrint(array $stmts): string {
  248. $this->resetState();
  249. $this->preprocessNodes($stmts);
  250. return ltrim($this->handleMagicTokens($this->pStmts($stmts, false)));
  251. }
  252. /**
  253. * Pretty prints an expression.
  254. *
  255. * @param Expr $node Expression node
  256. *
  257. * @return string Pretty printed node
  258. */
  259. public function prettyPrintExpr(Expr $node): string {
  260. $this->resetState();
  261. return $this->handleMagicTokens($this->p($node));
  262. }
  263. /**
  264. * Pretty prints a file of statements (includes the opening <?php tag if it is required).
  265. *
  266. * @param Node[] $stmts Array of statements
  267. *
  268. * @return string Pretty printed statements
  269. */
  270. public function prettyPrintFile(array $stmts): string {
  271. if (!$stmts) {
  272. return "<?php" . $this->newline . $this->newline;
  273. }
  274. $p = "<?php" . $this->newline . $this->newline . $this->prettyPrint($stmts);
  275. if ($stmts[0] instanceof Stmt\InlineHTML) {
  276. $p = preg_replace('/^<\?php\s+\?>\r?\n?/', '', $p);
  277. }
  278. if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) {
  279. $p = preg_replace('/<\?php$/', '', rtrim($p));
  280. }
  281. return $p;
  282. }
  283. /**
  284. * Preprocesses the top-level nodes to initialize pretty printer state.
  285. *
  286. * @param Node[] $nodes Array of nodes
  287. */
  288. protected function preprocessNodes(array $nodes): void {
  289. /* We can use semicolon-namespaces unless there is a global namespace declaration */
  290. $this->canUseSemicolonNamespaces = true;
  291. foreach ($nodes as $node) {
  292. if ($node instanceof Stmt\Namespace_ && null === $node->name) {
  293. $this->canUseSemicolonNamespaces = false;
  294. break;
  295. }
  296. }
  297. }
  298. /**
  299. * Handles (and removes) doc-string-end tokens.
  300. */
  301. protected function handleMagicTokens(string $str): string {
  302. if ($this->docStringEndToken !== null) {
  303. // Replace doc-string-end tokens with nothing or a newline
  304. $str = str_replace(
  305. $this->docStringEndToken . ';' . $this->newline,
  306. ';' . $this->newline,
  307. $str);
  308. $str = str_replace($this->docStringEndToken, $this->newline, $str);
  309. }
  310. return $str;
  311. }
  312. /**
  313. * Pretty prints an array of nodes (statements) and indents them optionally.
  314. *
  315. * @param Node[] $nodes Array of nodes
  316. * @param bool $indent Whether to indent the printed nodes
  317. *
  318. * @return string Pretty printed statements
  319. */
  320. protected function pStmts(array $nodes, bool $indent = true): string {
  321. if ($indent) {
  322. $this->indent();
  323. }
  324. $result = '';
  325. foreach ($nodes as $node) {
  326. $comments = $node->getComments();
  327. if ($comments) {
  328. $result .= $this->nl . $this->pComments($comments);
  329. if ($node instanceof Stmt\Nop) {
  330. continue;
  331. }
  332. }
  333. $result .= $this->nl . $this->p($node);
  334. }
  335. if ($indent) {
  336. $this->outdent();
  337. }
  338. return $result;
  339. }
  340. /**
  341. * Pretty-print an infix operation while taking precedence into account.
  342. *
  343. * @param string $class Node class of operator
  344. * @param Node $leftNode Left-hand side node
  345. * @param string $operatorString String representation of the operator
  346. * @param Node $rightNode Right-hand side node
  347. * @param int $precedence Precedence of parent operator
  348. * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator
  349. *
  350. * @return string Pretty printed infix operation
  351. */
  352. protected function pInfixOp(
  353. string $class, Node $leftNode, string $operatorString, Node $rightNode,
  354. int $precedence, int $lhsPrecedence
  355. ): string {
  356. list($opPrecedence, $newPrecedenceLHS, $newPrecedenceRHS) = $this->precedenceMap[$class];
  357. $prefix = '';
  358. $suffix = '';
  359. if ($opPrecedence >= $precedence) {
  360. $prefix = '(';
  361. $suffix = ')';
  362. $lhsPrecedence = self::MAX_PRECEDENCE;
  363. }
  364. return $prefix . $this->p($leftNode, $newPrecedenceLHS, $newPrecedenceLHS)
  365. . $operatorString . $this->p($rightNode, $newPrecedenceRHS, $lhsPrecedence) . $suffix;
  366. }
  367. /**
  368. * Pretty-print a prefix operation while taking precedence into account.
  369. *
  370. * @param string $class Node class of operator
  371. * @param string $operatorString String representation of the operator
  372. * @param Node $node Node
  373. * @param int $precedence Precedence of parent operator
  374. * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator
  375. *
  376. * @return string Pretty printed prefix operation
  377. */
  378. protected function pPrefixOp(string $class, string $operatorString, Node $node, int $precedence, int $lhsPrecedence): string {
  379. $opPrecedence = $this->precedenceMap[$class][0];
  380. $prefix = '';
  381. $suffix = '';
  382. if ($opPrecedence >= $lhsPrecedence) {
  383. $prefix = '(';
  384. $suffix = ')';
  385. $lhsPrecedence = self::MAX_PRECEDENCE;
  386. }
  387. $printedArg = $this->p($node, $opPrecedence, $lhsPrecedence);
  388. if (($operatorString === '+' && $printedArg[0] === '+') ||
  389. ($operatorString === '-' && $printedArg[0] === '-')
  390. ) {
  391. // Avoid printing +(+$a) as ++$a and similar.
  392. $printedArg = '(' . $printedArg . ')';
  393. }
  394. return $prefix . $operatorString . $printedArg . $suffix;
  395. }
  396. /**
  397. * Pretty-print a postfix operation while taking precedence into account.
  398. *
  399. * @param string $class Node class of operator
  400. * @param string $operatorString String representation of the operator
  401. * @param Node $node Node
  402. * @param int $precedence Precedence of parent operator
  403. * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator
  404. *
  405. * @return string Pretty printed postfix operation
  406. */
  407. protected function pPostfixOp(string $class, Node $node, string $operatorString, int $precedence, int $lhsPrecedence): string {
  408. $opPrecedence = $this->precedenceMap[$class][0];
  409. $prefix = '';
  410. $suffix = '';
  411. if ($opPrecedence >= $precedence) {
  412. $prefix = '(';
  413. $suffix = ')';
  414. $lhsPrecedence = self::MAX_PRECEDENCE;
  415. }
  416. if ($opPrecedence < $lhsPrecedence) {
  417. $lhsPrecedence = $opPrecedence;
  418. }
  419. return $prefix . $this->p($node, $opPrecedence, $lhsPrecedence) . $operatorString . $suffix;
  420. }
  421. /**
  422. * Pretty prints an array of nodes and implodes the printed values.
  423. *
  424. * @param Node[] $nodes Array of Nodes to be printed
  425. * @param string $glue Character to implode with
  426. *
  427. * @return string Imploded pretty printed nodes> $pre
  428. */
  429. protected function pImplode(array $nodes, string $glue = ''): string {
  430. $pNodes = [];
  431. foreach ($nodes as $node) {
  432. if (null === $node) {
  433. $pNodes[] = '';
  434. } else {
  435. $pNodes[] = $this->p($node);
  436. }
  437. }
  438. return implode($glue, $pNodes);
  439. }
  440. /**
  441. * Pretty prints an array of nodes and implodes the printed values with commas.
  442. *
  443. * @param Node[] $nodes Array of Nodes to be printed
  444. *
  445. * @return string Comma separated pretty printed nodes
  446. */
  447. protected function pCommaSeparated(array $nodes): string {
  448. return $this->pImplode($nodes, ', ');
  449. }
  450. /**
  451. * Pretty prints a comma-separated list of nodes in multiline style, including comments.
  452. *
  453. * The result includes a leading newline and one level of indentation (same as pStmts).
  454. *
  455. * @param Node[] $nodes Array of Nodes to be printed
  456. * @param bool $trailingComma Whether to use a trailing comma
  457. *
  458. * @return string Comma separated pretty printed nodes in multiline style
  459. */
  460. protected function pCommaSeparatedMultiline(array $nodes, bool $trailingComma): string {
  461. $this->indent();
  462. $result = '';
  463. $lastIdx = count($nodes) - 1;
  464. foreach ($nodes as $idx => $node) {
  465. if ($node !== null) {
  466. $comments = $node->getComments();
  467. if ($comments) {
  468. $result .= $this->nl . $this->pComments($comments);
  469. }
  470. $result .= $this->nl . $this->p($node);
  471. } else {
  472. $result .= $this->nl;
  473. }
  474. if ($trailingComma || $idx !== $lastIdx) {
  475. $result .= ',';
  476. }
  477. }
  478. $this->outdent();
  479. return $result;
  480. }
  481. /**
  482. * Prints reformatted text of the passed comments.
  483. *
  484. * @param Comment[] $comments List of comments
  485. *
  486. * @return string Reformatted text of comments
  487. */
  488. protected function pComments(array $comments): string {
  489. $formattedComments = [];
  490. foreach ($comments as $comment) {
  491. $formattedComments[] = str_replace("\n", $this->nl, $comment->getReformattedText());
  492. }
  493. return implode($this->nl, $formattedComments);
  494. }
  495. /**
  496. * Perform a format-preserving pretty print of an AST.
  497. *
  498. * The format preservation is best effort. For some changes to the AST the formatting will not
  499. * be preserved (at least not locally).
  500. *
  501. * In order to use this method a number of prerequisites must be satisfied:
  502. * * The startTokenPos and endTokenPos attributes in the lexer must be enabled.
  503. * * The CloningVisitor must be run on the AST prior to modification.
  504. * * The original tokens must be provided, using the getTokens() method on the lexer.
  505. *
  506. * @param Node[] $stmts Modified AST with links to original AST
  507. * @param Node[] $origStmts Original AST with token offset information
  508. * @param Token[] $origTokens Tokens of the original code
  509. */
  510. public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string {
  511. $this->initializeNodeListDiffer();
  512. $this->initializeLabelCharMap();
  513. $this->initializeFixupMap();
  514. $this->initializeRemovalMap();
  515. $this->initializeInsertionMap();
  516. $this->initializeListInsertionMap();
  517. $this->initializeEmptyListInsertionMap();
  518. $this->initializeModifierChangeMap();
  519. $this->resetState();
  520. $this->origTokens = new TokenStream($origTokens, $this->tabWidth);
  521. $this->preprocessNodes($stmts);
  522. $pos = 0;
  523. $result = $this->pArray($stmts, $origStmts, $pos, 0, 'File', 'stmts', null);
  524. if (null !== $result) {
  525. $result .= $this->origTokens->getTokenCode($pos, count($origTokens) - 1, 0);
  526. } else {
  527. // Fallback
  528. // TODO Add <?php properly
  529. $result = "<?php" . $this->newline . $this->pStmts($stmts, false);
  530. }
  531. return $this->handleMagicTokens($result);
  532. }
  533. protected function pFallback(Node $node, int $precedence, int $lhsPrecedence): string {
  534. return $this->{'p' . $node->getType()}($node, $precedence, $lhsPrecedence);
  535. }
  536. /**
  537. * Pretty prints a node.
  538. *
  539. * This method also handles formatting preservation for nodes.
  540. *
  541. * @param Node $node Node to be pretty printed
  542. * @param int $precedence Precedence of parent operator
  543. * @param int $lhsPrecedence Precedence for unary operator on LHS of binary operator
  544. * @param bool $parentFormatPreserved Whether parent node has preserved formatting
  545. *
  546. * @return string Pretty printed node
  547. */
  548. protected function p(
  549. Node $node, int $precedence = self::MAX_PRECEDENCE, int $lhsPrecedence = self::MAX_PRECEDENCE,
  550. bool $parentFormatPreserved = false
  551. ): string {
  552. // No orig tokens means this is a normal pretty print without preservation of formatting
  553. if (!$this->origTokens) {
  554. return $this->{'p' . $node->getType()}($node, $precedence, $lhsPrecedence);
  555. }
  556. /** @var Node|null $origNode */
  557. $origNode = $node->getAttribute('origNode');
  558. if (null === $origNode) {
  559. return $this->pFallback($node, $precedence, $lhsPrecedence);
  560. }
  561. $class = \get_class($node);
  562. \assert($class === \get_class($origNode));
  563. $startPos = $origNode->getStartTokenPos();
  564. $endPos = $origNode->getEndTokenPos();
  565. \assert($startPos >= 0 && $endPos >= 0);
  566. $fallbackNode = $node;
  567. if ($node instanceof Expr\New_ && $node->class instanceof Stmt\Class_) {
  568. // Normalize node structure of anonymous classes
  569. assert($origNode instanceof Expr\New_);
  570. $node = PrintableNewAnonClassNode::fromNewNode($node);
  571. $origNode = PrintableNewAnonClassNode::fromNewNode($origNode);
  572. $class = PrintableNewAnonClassNode::class;
  573. }
  574. // InlineHTML node does not contain closing and opening PHP tags. If the parent formatting
  575. // is not preserved, then we need to use the fallback code to make sure the tags are
  576. // printed.
  577. if ($node instanceof Stmt\InlineHTML && !$parentFormatPreserved) {
  578. return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence);
  579. }
  580. $indentAdjustment = $this->indentLevel - $this->origTokens->getIndentationBefore($startPos);
  581. $type = $node->getType();
  582. $fixupInfo = $this->fixupMap[$class] ?? null;
  583. $result = '';
  584. $pos = $startPos;
  585. foreach ($node->getSubNodeNames() as $subNodeName) {
  586. $subNode = $node->$subNodeName;
  587. $origSubNode = $origNode->$subNodeName;
  588. if ((!$subNode instanceof Node && $subNode !== null)
  589. || (!$origSubNode instanceof Node && $origSubNode !== null)
  590. ) {
  591. if ($subNode === $origSubNode) {
  592. // Unchanged, can reuse old code
  593. continue;
  594. }
  595. if (is_array($subNode) && is_array($origSubNode)) {
  596. // Array subnode changed, we might be able to reconstruct it
  597. $listResult = $this->pArray(
  598. $subNode, $origSubNode, $pos, $indentAdjustment, $class, $subNodeName,
  599. $fixupInfo[$subNodeName] ?? null
  600. );
  601. if (null === $listResult) {
  602. return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence);
  603. }
  604. $result .= $listResult;
  605. continue;
  606. }
  607. // Check if this is a modifier change
  608. $key = $class . '->' . $subNodeName;
  609. if (!isset($this->modifierChangeMap[$key])) {
  610. return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence);
  611. }
  612. [$printFn, $findToken] = $this->modifierChangeMap[$key];
  613. $result .= $this->$printFn($subNode);
  614. $pos = $this->origTokens->findRight($pos, $findToken);
  615. continue;
  616. }
  617. $extraLeft = '';
  618. $extraRight = '';
  619. if ($origSubNode !== null) {
  620. $subStartPos = $origSubNode->getStartTokenPos();
  621. $subEndPos = $origSubNode->getEndTokenPos();
  622. \assert($subStartPos >= 0 && $subEndPos >= 0);
  623. } else {
  624. if ($subNode === null) {
  625. // Both null, nothing to do
  626. continue;
  627. }
  628. // A node has been inserted, check if we have insertion information for it
  629. $key = $type . '->' . $subNodeName;
  630. if (!isset($this->insertionMap[$key])) {
  631. return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence);
  632. }
  633. list($findToken, $beforeToken, $extraLeft, $extraRight) = $this->insertionMap[$key];
  634. if (null !== $findToken) {
  635. $subStartPos = $this->origTokens->findRight($pos, $findToken)
  636. + (int) !$beforeToken;
  637. } else {
  638. $subStartPos = $pos;
  639. }
  640. if (null === $extraLeft && null !== $extraRight) {
  641. // If inserting on the right only, skipping whitespace looks better
  642. $subStartPos = $this->origTokens->skipRightWhitespace($subStartPos);
  643. }
  644. $subEndPos = $subStartPos - 1;
  645. }
  646. if (null === $subNode) {
  647. // A node has been removed, check if we have removal information for it
  648. $key = $type . '->' . $subNodeName;
  649. if (!isset($this->removalMap[$key])) {
  650. return $this->pFallback($fallbackNode, $precedence, $lhsPrecedence);
  651. }
  652. // Adjust positions to account for additional tokens that must be skipped
  653. $removalInfo = $this->removalMap[$key];
  654. if (isset($removalInfo['left'])) {
  655. $subStartPos = $this->origTokens->skipLeft($subStartPos - 1, $removalInfo['left']) + 1;
  656. }
  657. if (isset($removalInfo['right'])) {
  658. $subEndPos = $this->origTokens->skipRight($subEndPos + 1, $removalInfo['right']) - 1;
  659. }
  660. }
  661. $result .= $this->origTokens->getTokenCode($pos, $subStartPos, $indentAdjustment);
  662. if (null !== $subNode) {
  663. $result .= $extraLeft;
  664. $origIndentLevel = $this->indentLevel;
  665. $this->setIndentLevel(max($this->origTokens->getIndentationBefore($subStartPos) + $indentAdjustment, 0));
  666. // If it's the same node that was previously in this position, it certainly doesn't
  667. // need fixup. It's important to check this here, because our fixup checks are more
  668. // conservative than strictly necessary.
  669. if (isset($fixupInfo[$subNodeName])
  670. && $subNode->getAttribute('origNode') !== $origSubNode
  671. ) {
  672. $fixup = $fixupInfo[$subNodeName];
  673. $res = $this->pFixup($fixup, $subNode, $class, $subStartPos, $subEndPos);
  674. } else {
  675. $res = $this->p($subNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true);
  676. }
  677. $this->safeAppend($result, $res);
  678. $this->setIndentLevel($origIndentLevel);
  679. $result .= $extraRight;
  680. }
  681. $pos = $subEndPos + 1;
  682. }
  683. $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment);
  684. return $result;
  685. }
  686. /**
  687. * Perform a format-preserving pretty print of an array.
  688. *
  689. * @param Node[] $nodes New nodes
  690. * @param Node[] $origNodes Original nodes
  691. * @param int $pos Current token position (updated by reference)
  692. * @param int $indentAdjustment Adjustment for indentation
  693. * @param string $parentNodeClass Class of the containing node.
  694. * @param string $subNodeName Name of array subnode.
  695. * @param null|int $fixup Fixup information for array item nodes
  696. *
  697. * @return null|string Result of pretty print or null if cannot preserve formatting
  698. */
  699. protected function pArray(
  700. array $nodes, array $origNodes, int &$pos, int $indentAdjustment,
  701. string $parentNodeClass, string $subNodeName, ?int $fixup
  702. ): ?string {
  703. $diff = $this->nodeListDiffer->diffWithReplacements($origNodes, $nodes);
  704. $mapKey = $parentNodeClass . '->' . $subNodeName;
  705. $insertStr = $this->listInsertionMap[$mapKey] ?? null;
  706. $isStmtList = $subNodeName === 'stmts';
  707. $beforeFirstKeepOrReplace = true;
  708. $skipRemovedNode = false;
  709. $delayedAdd = [];
  710. $lastElemIndentLevel = $this->indentLevel;
  711. $insertNewline = false;
  712. if ($insertStr === "\n") {
  713. $insertStr = '';
  714. $insertNewline = true;
  715. }
  716. if ($isStmtList && \count($origNodes) === 1 && \count($nodes) !== 1) {
  717. $startPos = $origNodes[0]->getStartTokenPos();
  718. $endPos = $origNodes[0]->getEndTokenPos();
  719. \assert($startPos >= 0 && $endPos >= 0);
  720. if (!$this->origTokens->haveBraces($startPos, $endPos)) {
  721. // This was a single statement without braces, but either additional statements
  722. // have been added, or the single statement has been removed. This requires the
  723. // addition of braces. For now fall back.
  724. // TODO: Try to preserve formatting
  725. return null;
  726. }
  727. }
  728. $result = '';
  729. foreach ($diff as $i => $diffElem) {
  730. $diffType = $diffElem->type;
  731. /** @var Node|string|null $arrItem */
  732. $arrItem = $diffElem->new;
  733. /** @var Node|string|null $origArrItem */
  734. $origArrItem = $diffElem->old;
  735. if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
  736. $beforeFirstKeepOrReplace = false;
  737. if ($origArrItem === null || $arrItem === null) {
  738. // We can only handle the case where both are null
  739. if ($origArrItem === $arrItem) {
  740. continue;
  741. }
  742. return null;
  743. }
  744. if (!$arrItem instanceof Node || !$origArrItem instanceof Node) {
  745. // We can only deal with nodes. This can occur for Names, which use string arrays.
  746. return null;
  747. }
  748. $itemStartPos = $origArrItem->getStartTokenPos();
  749. $itemEndPos = $origArrItem->getEndTokenPos();
  750. \assert($itemStartPos >= 0 && $itemEndPos >= 0 && $itemStartPos >= $pos);
  751. $origIndentLevel = $this->indentLevel;
  752. $lastElemIndentLevel = max($this->origTokens->getIndentationBefore($itemStartPos) + $indentAdjustment, 0);
  753. $this->setIndentLevel($lastElemIndentLevel);
  754. $comments = $arrItem->getComments();
  755. $origComments = $origArrItem->getComments();
  756. $commentStartPos = $origComments ? $origComments[0]->getStartTokenPos() : $itemStartPos;
  757. \assert($commentStartPos >= 0);
  758. if ($commentStartPos < $pos) {
  759. // Comments may be assigned to multiple nodes if they start at the same position.
  760. // Make sure we don't try to print them multiple times.
  761. $commentStartPos = $itemStartPos;
  762. }
  763. if ($skipRemovedNode) {
  764. if ($isStmtList && $this->origTokens->haveTagInRange($pos, $itemStartPos)) {
  765. // We'd remove an opening/closing PHP tag.
  766. // TODO: Preserve formatting.
  767. $this->setIndentLevel($origIndentLevel);
  768. return null;
  769. }
  770. } else {
  771. $result .= $this->origTokens->getTokenCode(
  772. $pos, $commentStartPos, $indentAdjustment);
  773. }
  774. if (!empty($delayedAdd)) {
  775. /** @var Node $delayedAddNode */
  776. foreach ($delayedAdd as $delayedAddNode) {
  777. if ($insertNewline) {
  778. $delayedAddComments = $delayedAddNode->getComments();
  779. if ($delayedAddComments) {
  780. $result .= $this->pComments($delayedAddComments) . $this->nl;
  781. }
  782. }
  783. $this->safeAppend($result, $this->p($delayedAddNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true));
  784. if ($insertNewline) {
  785. $result .= $insertStr . $this->nl;
  786. } else {
  787. $result .= $insertStr;
  788. }
  789. }
  790. $delayedAdd = [];
  791. }
  792. if ($comments !== $origComments) {
  793. if ($comments) {
  794. $result .= $this->pComments($comments) . $this->nl;
  795. }
  796. } else {
  797. $result .= $this->origTokens->getTokenCode(
  798. $commentStartPos, $itemStartPos, $indentAdjustment);
  799. }
  800. // If we had to remove anything, we have done so now.
  801. $skipRemovedNode = false;
  802. } elseif ($diffType === DiffElem::TYPE_ADD) {
  803. if (null === $insertStr) {
  804. // We don't have insertion information for this list type
  805. return null;
  806. }
  807. if (!$arrItem instanceof Node) {
  808. // We only support list insertion of nodes.
  809. return null;
  810. }
  811. // We go multiline if the original code was multiline,
  812. // or if it's an array item with a comment above it.
  813. // Match always uses multiline formatting.
  814. if ($insertStr === ', ' &&
  815. ($this->isMultiline($origNodes) || $arrItem->getComments() ||
  816. $parentNodeClass === Expr\Match_::class)
  817. ) {
  818. $insertStr = ',';
  819. $insertNewline = true;
  820. }
  821. if ($beforeFirstKeepOrReplace) {
  822. // Will be inserted at the next "replace" or "keep" element
  823. $delayedAdd[] = $arrItem;
  824. continue;
  825. }
  826. $itemStartPos = $pos;
  827. $itemEndPos = $pos - 1;
  828. $origIndentLevel = $this->indentLevel;
  829. $this->setIndentLevel($lastElemIndentLevel);
  830. if ($insertNewline) {
  831. $result .= $insertStr . $this->nl;
  832. $comments = $arrItem->getComments();
  833. if ($comments) {
  834. $result .= $this->pComments($comments) . $this->nl;
  835. }
  836. } else {
  837. $result .= $insertStr;
  838. }
  839. } elseif ($diffType === DiffElem::TYPE_REMOVE) {
  840. if (!$origArrItem instanceof Node) {
  841. // We only support removal for nodes
  842. return null;
  843. }
  844. $itemStartPos = $origArrItem->getStartTokenPos();
  845. $itemEndPos = $origArrItem->getEndTokenPos();
  846. \assert($itemStartPos >= 0 && $itemEndPos >= 0);
  847. // Consider comments part of the node.
  848. $origComments = $origArrItem->getComments();
  849. if ($origComments) {
  850. $itemStartPos = $origComments[0]->getStartTokenPos();
  851. }
  852. if ($i === 0) {
  853. // If we're removing from the start, keep the tokens before the node and drop those after it,
  854. // instead of the other way around.
  855. $result .= $this->origTokens->getTokenCode(
  856. $pos, $itemStartPos, $indentAdjustment);
  857. $skipRemovedNode = true;
  858. } else {
  859. if ($isStmtList && $this->origTokens->haveTagInRange($pos, $itemStartPos)) {
  860. // We'd remove an opening/closing PHP tag.
  861. // TODO: Preserve formatting.
  862. return null;
  863. }
  864. }
  865. $pos = $itemEndPos + 1;
  866. continue;
  867. } else {
  868. throw new \Exception("Shouldn't happen");
  869. }
  870. if (null !== $fixup && $arrItem->getAttribute('origNode') !== $origArrItem) {
  871. $res = $this->pFixup($fixup, $arrItem, null, $itemStartPos, $itemEndPos);
  872. } else {
  873. $res = $this->p($arrItem, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true);
  874. }
  875. $this->safeAppend($result, $res);
  876. $this->setIndentLevel($origIndentLevel);
  877. $pos = $itemEndPos + 1;
  878. }
  879. if ($skipRemovedNode) {
  880. // TODO: Support removing single node.
  881. return null;
  882. }
  883. if (!empty($delayedAdd)) {
  884. if (!isset($this->emptyListInsertionMap[$mapKey])) {
  885. return null;
  886. }
  887. list($findToken, $extraLeft, $extraRight) = $this->emptyListInsertionMap[$mapKey];
  888. if (null !== $findToken) {
  889. $insertPos = $this->origTokens->findRight($pos, $findToken) + 1;
  890. $result .= $this->origTokens->getTokenCode($pos, $insertPos, $indentAdjustment);
  891. $pos = $insertPos;
  892. }
  893. $first = true;
  894. $result .= $extraLeft;
  895. foreach ($delayedAdd as $delayedAddNode) {
  896. if (!$first) {
  897. $result .= $insertStr;
  898. if ($insertNewline) {
  899. $result .= $this->nl;
  900. }
  901. }
  902. $result .= $this->p($delayedAddNode, self::MAX_PRECEDENCE, self::MAX_PRECEDENCE, true);
  903. $first = false;
  904. }
  905. $result .= $extraRight === "\n" ? $this->nl : $extraRight;
  906. }
  907. return $result;
  908. }
  909. /**
  910. * Print node with fixups.
  911. *
  912. * Fixups here refer to the addition of extra parentheses, braces or other characters, that
  913. * are required to preserve program semantics in a certain context (e.g. to maintain precedence
  914. * or because only certain expressions are allowed in certain places).
  915. *
  916. * @param int $fixup Fixup type
  917. * @param Node $subNode Subnode to print
  918. * @param string|null $parentClass Class of parent node
  919. * @param int $subStartPos Original start pos of subnode
  920. * @param int $subEndPos Original end pos of subnode
  921. *
  922. * @return string Result of fixed-up print of subnode
  923. */
  924. protected function pFixup(int $fixup, Node $subNode, ?string $parentClass, int $subStartPos, int $subEndPos): string {
  925. switch ($fixup) {
  926. case self::FIXUP_PREC_LEFT:
  927. // We use a conservative approximation where lhsPrecedence == precedence.
  928. if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) {
  929. $precedence = $this->precedenceMap[$parentClass][1];
  930. return $this->p($subNode, $precedence, $precedence);
  931. }
  932. break;
  933. case self::FIXUP_PREC_RIGHT:
  934. if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) {
  935. $precedence = $this->precedenceMap[$parentClass][2];
  936. return $this->p($subNode, $precedence, $precedence);
  937. }
  938. break;
  939. case self::FIXUP_PREC_UNARY:
  940. if (!$this->origTokens->haveParens($subStartPos, $subEndPos)) {
  941. $precedence = $this->precedenceMap[$parentClass][0];
  942. return $this->p($subNode, $precedence, $precedence);
  943. }
  944. break;
  945. case self::FIXUP_CALL_LHS:
  946. if ($this->callLhsRequiresParens($subNode)
  947. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  948. ) {
  949. return '(' . $this->p($subNode) . ')';
  950. }
  951. break;
  952. case self::FIXUP_DEREF_LHS:
  953. if ($this->dereferenceLhsRequiresParens($subNode)
  954. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  955. ) {
  956. return '(' . $this->p($subNode) . ')';
  957. }
  958. break;
  959. case self::FIXUP_STATIC_DEREF_LHS:
  960. if ($this->staticDereferenceLhsRequiresParens($subNode)
  961. && !$this->origTokens->haveParens($subStartPos, $subEndPos)
  962. ) {
  963. return '(' . $this->p($subNode) . ')';
  964. }
  965. break;
  966. case self::FIXUP_NEW:
  967. if ($this->newOperandRequiresParens($subNode)
  968. && !$this->origTokens->haveParens($subStartPos, $subEndPos)) {
  969. return '(' . $this->p($subNode) . ')';
  970. }
  971. break;
  972. case self::FIXUP_BRACED_NAME:
  973. case self::FIXUP_VAR_BRACED_NAME:
  974. if ($subNode instanceof Expr
  975. && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
  976. ) {
  977. return ($fixup === self::FIXUP_VAR_BRACED_NAME ? '$' : '')
  978. . '{' . $this->p($subNode) . '}';
  979. }
  980. break;
  981. case self::FIXUP_ENCAPSED:
  982. if (!$subNode instanceof Node\InterpolatedStringPart
  983. && !$this->origTokens->haveBraces($subStartPos, $subEndPos)
  984. ) {
  985. return '{' . $this->p($subNode) . '}';
  986. }
  987. break;
  988. default:
  989. throw new \Exception('Cannot happen');
  990. }
  991. // Nothing special to do
  992. return $this->p($subNode);
  993. }
  994. /**
  995. * Appends to a string, ensuring whitespace between label characters.
  996. *
  997. * Example: "echo" and "$x" result in "echo$x", but "echo" and "x" result in "echo x".
  998. * Without safeAppend the result would be "echox", which does not preserve semantics.
  999. */
  1000. protected function safeAppend(string &$str, string $append): void {
  1001. if ($str === "") {
  1002. $str = $append;
  1003. return;
  1004. }
  1005. if ($append === "") {
  1006. return;
  1007. }
  1008. if (!$this->labelCharMap[$append[0]]
  1009. || !$this->labelCharMap[$str[\strlen($str) - 1]]) {
  1010. $str .= $append;
  1011. } else {
  1012. $str .= " " . $append;
  1013. }
  1014. }
  1015. /**
  1016. * Determines whether the LHS of a call must be wrapped in parenthesis.
  1017. *
  1018. * @param Node $node LHS of a call
  1019. *
  1020. * @return bool Whether parentheses are required
  1021. */
  1022. protected function callLhsRequiresParens(Node $node): bool {
  1023. return !($node instanceof Node\Name
  1024. || $node instanceof Expr\Variable
  1025. || $node instanceof Expr\ArrayDimFetch
  1026. || $node instanceof Expr\FuncCall
  1027. || $node instanceof Expr\MethodCall
  1028. || $node instanceof Expr\NullsafeMethodCall
  1029. || $node instanceof Expr\StaticCall
  1030. || $node instanceof Expr\Array_);
  1031. }
  1032. /**
  1033. * Determines whether the LHS of an array/object operation must be wrapped in parentheses.
  1034. *
  1035. * @param Node $node LHS of dereferencing operation
  1036. *
  1037. * @return bool Whether parentheses are required
  1038. */
  1039. protected function dereferenceLhsRequiresParens(Node $node): bool {
  1040. // A constant can occur on the LHS of an array/object deref, but not a static deref.
  1041. return $this->staticDereferenceLhsRequiresParens($node)
  1042. && !$node instanceof Expr\ConstFetch;
  1043. }
  1044. /**
  1045. * Determines whether the LHS of a static operation must be wrapped in parentheses.
  1046. *
  1047. * @param Node $node LHS of dereferencing operation
  1048. *
  1049. * @return bool Whether parentheses are required
  1050. */
  1051. protected function staticDereferenceLhsRequiresParens(Node $node): bool {
  1052. return !($node instanceof Expr\Variable
  1053. || $node instanceof Node\Name
  1054. || $node instanceof Expr\ArrayDimFetch
  1055. || $node instanceof Expr\PropertyFetch
  1056. || $node instanceof Expr\NullsafePropertyFetch
  1057. || $node instanceof Expr\StaticPropertyFetch
  1058. || $node instanceof Expr\FuncCall
  1059. || $node instanceof Expr\MethodCall
  1060. || $node instanceof Expr\NullsafeMethodCall
  1061. || $node instanceof Expr\StaticCall
  1062. || $node instanceof Expr\Array_
  1063. || $node instanceof Scalar\String_
  1064. || $node instanceof Expr\ClassConstFetch);
  1065. }
  1066. /**
  1067. * Determines whether an expression used in "new" or "instanceof" requires parentheses.
  1068. *
  1069. * @param Node $node New or instanceof operand
  1070. *
  1071. * @return bool Whether parentheses are required
  1072. */
  1073. protected function newOperandRequiresParens(Node $node): bool {
  1074. if ($node instanceof Node\Name || $node instanceof Expr\Variable) {
  1075. return false;
  1076. }
  1077. if ($node instanceof Expr\ArrayDimFetch || $node instanceof Expr\PropertyFetch ||
  1078. $node instanceof Expr\NullsafePropertyFetch
  1079. ) {
  1080. return $this->newOperandRequiresParens($node->var);
  1081. }
  1082. if ($node instanceof Expr\StaticPropertyFetch) {
  1083. return $this->newOperandRequiresParens($node->class);
  1084. }
  1085. return true;
  1086. }
  1087. /**
  1088. * Print modifiers, including trailing whitespace.
  1089. *
  1090. * @param int $modifiers Modifier mask to print
  1091. *
  1092. * @return string Printed modifiers
  1093. */
  1094. protected function pModifiers(int $modifiers): string {
  1095. return ($modifiers & Modifiers::FINAL ? 'final ' : '')
  1096. . ($modifiers & Modifiers::ABSTRACT ? 'abstract ' : '')
  1097. . ($modifiers & Modifiers::PUBLIC ? 'public ' : '')
  1098. . ($modifiers & Modifiers::PROTECTED ? 'protected ' : '')
  1099. . ($modifiers & Modifiers::PRIVATE ? 'private ' : '')
  1100. . ($modifiers & Modifiers::PUBLIC_SET ? 'public(set) ' : '')
  1101. . ($modifiers & Modifiers::PROTECTED_SET ? 'protected(set) ' : '')
  1102. . ($modifiers & Modifiers::PRIVATE_SET ? 'private(set) ' : '')
  1103. . ($modifiers & Modifiers::STATIC ? 'static ' : '')
  1104. . ($modifiers & Modifiers::READONLY ? 'readonly ' : '');
  1105. }
  1106. protected function pStatic(bool $static): string {
  1107. return $static ? 'static ' : '';
  1108. }
  1109. /**
  1110. * Determine whether a list of nodes uses multiline formatting.
  1111. *
  1112. * @param (Node|null)[] $nodes Node list
  1113. *
  1114. * @return bool Whether multiline formatting is used
  1115. */
  1116. protected function isMultiline(array $nodes): bool {
  1117. if (\count($nodes) < 2) {
  1118. return false;
  1119. }
  1120. $pos = -1;
  1121. foreach ($nodes as $node) {
  1122. if (null === $node) {
  1123. continue;
  1124. }
  1125. $endPos = $node->getEndTokenPos() + 1;
  1126. if ($pos >= 0) {
  1127. $text = $this->origTokens->getTokenCode($pos, $endPos, 0);
  1128. if (false === strpos($text, "\n")) {
  1129. // We require that a newline is present between *every* item. If the formatting
  1130. // is inconsistent, with only some items having newlines, we don't consider it
  1131. // as multiline
  1132. return false;
  1133. }
  1134. }
  1135. $pos = $endPos;
  1136. }
  1137. return true;
  1138. }
  1139. /**
  1140. * Lazily initializes label char map.
  1141. *
  1142. * The label char map determines whether a certain character may occur in a label.
  1143. */
  1144. protected function initializeLabelCharMap(): void {
  1145. if (isset($this->labelCharMap)) {
  1146. return;
  1147. }
  1148. $this->labelCharMap = [];
  1149. for ($i = 0; $i < 256; $i++) {
  1150. $chr = chr($i);
  1151. $this->labelCharMap[$chr] = $i >= 0x80 || ctype_alnum($chr);
  1152. }
  1153. if ($this->phpVersion->allowsDelInIdentifiers()) {
  1154. $this->labelCharMap["\x7f"] = true;
  1155. }
  1156. }
  1157. /**
  1158. * Lazily initializes node list differ.
  1159. *
  1160. * The node list differ is used to determine differences between two array subnodes.
  1161. */
  1162. protected function initializeNodeListDiffer(): void {
  1163. if (isset($this->nodeListDiffer)) {
  1164. return;
  1165. }
  1166. $this->nodeListDiffer = new Internal\Differ(function ($a, $b) {
  1167. if ($a instanceof Node && $b instanceof Node) {
  1168. return $a === $b->getAttribute('origNode');
  1169. }
  1170. // Can happen for array destructuring
  1171. return $a === null && $b === null;
  1172. });
  1173. }
  1174. /**
  1175. * Lazily initializes fixup map.
  1176. *
  1177. * The fixup map is used to determine whether a certain subnode of a certain node may require
  1178. * some kind of "fixup" operation, e.g. the addition of parenthesis or braces.
  1179. */
  1180. protected function initializeFixupMap(): void {
  1181. if (isset($this->fixupMap)) {
  1182. return;
  1183. }
  1184. $this->fixupMap = [
  1185. Expr\Instanceof_::class => [
  1186. 'expr' => self::FIXUP_PREC_UNARY,
  1187. 'class' => self::FIXUP_NEW,
  1188. ],
  1189. Expr\Ternary::class => [
  1190. 'cond' => self::FIXUP_PREC_LEFT,
  1191. 'else' => self::FIXUP_PREC_RIGHT,
  1192. ],
  1193. Expr\Yield_::class => ['value' => self::FIXUP_PREC_UNARY],
  1194. Expr\FuncCall::class => ['name' => self::FIXUP_CALL_LHS],
  1195. Expr\StaticCall::class => ['class' => self::FIXUP_STATIC_DEREF_LHS],
  1196. Expr\ArrayDimFetch::class => ['var' => self::FIXUP_DEREF_LHS],
  1197. Expr\ClassConstFetch::class => [
  1198. 'class' => self::FIXUP_STATIC_DEREF_LHS,
  1199. 'name' => self::FIXUP_BRACED_NAME,
  1200. ],
  1201. Expr\New_::class => ['class' => self::FIXUP_NEW],
  1202. Expr\MethodCall::class => [
  1203. 'var' => self::FIXUP_DEREF_LHS,
  1204. 'name' => self::FIXUP_BRACED_NAME,
  1205. ],
  1206. Expr\NullsafeMethodCall::class => [
  1207. 'var' => self::FIXUP_DEREF_LHS,
  1208. 'name' => self::FIXUP_BRACED_NAME,
  1209. ],
  1210. Expr\StaticPropertyFetch::class => [
  1211. 'class' => self::FIXUP_STATIC_DEREF_LHS,
  1212. 'name' => self::FIXUP_VAR_BRACED_NAME,
  1213. ],
  1214. Expr\PropertyFetch::class => [
  1215. 'var' => self::FIXUP_DEREF_LHS,
  1216. 'name' => self::FIXUP_BRACED_NAME,
  1217. ],
  1218. Expr\NullsafePropertyFetch::class => [
  1219. 'var' => self::FIXUP_DEREF_LHS,
  1220. 'name' => self::FIXUP_BRACED_NAME,
  1221. ],
  1222. Scalar\InterpolatedString::class => [
  1223. 'parts' => self::FIXUP_ENCAPSED,
  1224. ],
  1225. ];
  1226. $binaryOps = [
  1227. BinaryOp\Pow::class, BinaryOp\Mul::class, BinaryOp\Div::class, BinaryOp\Mod::class,
  1228. BinaryOp\Plus::class, BinaryOp\Minus::class, BinaryOp\Concat::class,
  1229. BinaryOp\ShiftLeft::class, BinaryOp\ShiftRight::class, BinaryOp\Smaller::class,
  1230. BinaryOp\SmallerOrEqual::class, BinaryOp\Greater::class, BinaryOp\GreaterOrEqual::class,
  1231. BinaryOp\Equal::class, BinaryOp\NotEqual::class, BinaryOp\Identical::class,
  1232. BinaryOp\NotIdentical::class, BinaryOp\Spaceship::class, BinaryOp\BitwiseAnd::class,
  1233. BinaryOp\BitwiseXor::class, BinaryOp\BitwiseOr::class, BinaryOp\BooleanAnd::class,
  1234. BinaryOp\BooleanOr::class, BinaryOp\Coalesce::class, BinaryOp\LogicalAnd::class,
  1235. BinaryOp\LogicalXor::class, BinaryOp\LogicalOr::class,
  1236. ];
  1237. foreach ($binaryOps as $binaryOp) {
  1238. $this->fixupMap[$binaryOp] = [
  1239. 'left' => self::FIXUP_PREC_LEFT,
  1240. 'right' => self::FIXUP_PREC_RIGHT
  1241. ];
  1242. }
  1243. $prefixOps = [
  1244. Expr\Clone_::class, Expr\BitwiseNot::class, Expr\BooleanNot::class, Expr\UnaryPlus::class, Expr\UnaryMinus::class,
  1245. Cast\Int_::class, Cast\Double::class, Cast\String_::class, Cast\Array_::class,
  1246. Cast\Object_::class, Cast\Bool_::class, Cast\Unset_::class, Expr\ErrorSuppress::class,
  1247. Expr\YieldFrom::class, Expr\Print_::class, Expr\Include_::class,
  1248. Expr\Assign::class, Expr\AssignRef::class, AssignOp\Plus::class, AssignOp\Minus::class,
  1249. AssignOp\Mul::class, AssignOp\Div::class, AssignOp\Concat::class, AssignOp\Mod::class,
  1250. AssignOp\BitwiseAnd::class, AssignOp\BitwiseOr::class, AssignOp\BitwiseXor::class,
  1251. AssignOp\ShiftLeft::class, AssignOp\ShiftRight::class, AssignOp\Pow::class, AssignOp\Coalesce::class,
  1252. Expr\ArrowFunction::class, Expr\Throw_::class,
  1253. ];
  1254. foreach ($prefixOps as $prefixOp) {
  1255. $this->fixupMap[$prefixOp] = ['expr' => self::FIXUP_PREC_UNARY];
  1256. }
  1257. }
  1258. /**
  1259. * Lazily initializes the removal map.
  1260. *
  1261. * The removal map is used to determine which additional tokens should be removed when a
  1262. * certain node is replaced by null.
  1263. */
  1264. protected function initializeRemovalMap(): void {
  1265. if (isset($this->removalMap)) {
  1266. return;
  1267. }
  1268. $stripBoth = ['left' => \T_WHITESPACE, 'right' => \T_WHITESPACE];
  1269. $stripLeft = ['left' => \T_WHITESPACE];
  1270. $stripRight = ['right' => \T_WHITESPACE];
  1271. $stripDoubleArrow = ['right' => \T_DOUBLE_ARROW];
  1272. $stripColon = ['left' => ':'];
  1273. $stripEquals = ['left' => '='];
  1274. $this->removalMap = [
  1275. 'Expr_ArrayDimFetch->dim' => $stripBoth,
  1276. 'ArrayItem->key' => $stripDoubleArrow,
  1277. 'Expr_ArrowFunction->returnType' => $stripColon,
  1278. 'Expr_Closure->returnType' => $stripColon,
  1279. 'Expr_Exit->expr' => $stripBoth,
  1280. 'Expr_Ternary->if' => $stripBoth,
  1281. 'Expr_Yield->key' => $stripDoubleArrow,
  1282. 'Expr_Yield->value' => $stripBoth,
  1283. 'Param->type' => $stripRight,
  1284. 'Param->default' => $stripEquals,
  1285. 'Stmt_Break->num' => $stripBoth,
  1286. 'Stmt_Catch->var' => $stripLeft,
  1287. 'Stmt_ClassConst->type' => $stripRight,
  1288. 'Stmt_ClassMethod->returnType' => $stripColon,
  1289. 'Stmt_Class->extends' => ['left' => \T_EXTENDS],
  1290. 'Stmt_Enum->scalarType' => $stripColon,
  1291. 'Stmt_EnumCase->expr' => $stripEquals,
  1292. 'Expr_PrintableNewAnonClass->extends' => ['left' => \T_EXTENDS],
  1293. 'Stmt_Continue->num' => $stripBoth,
  1294. 'Stmt_Foreach->keyVar' => $stripDoubleArrow,
  1295. 'Stmt_Function->returnType' => $stripColon,
  1296. 'Stmt_If->else' => $stripLeft,
  1297. 'Stmt_Namespace->name' => $stripLeft,
  1298. 'Stmt_Property->type' => $stripRight,
  1299. 'PropertyItem->default' => $stripEquals,
  1300. 'Stmt_Return->expr' => $stripBoth,
  1301. 'Stmt_StaticVar->default' => $stripEquals,
  1302. 'Stmt_TraitUseAdaptation_Alias->newName' => $stripLeft,
  1303. 'Stmt_TryCatch->finally' => $stripLeft,
  1304. // 'Stmt_Case->cond': Replace with "default"
  1305. // 'Stmt_Class->name': Unclear what to do
  1306. // 'Stmt_Declare->stmts': Not a plain node
  1307. // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a plain node
  1308. ];
  1309. }
  1310. protected function initializeInsertionMap(): void {
  1311. if (isset($this->insertionMap)) {
  1312. return;
  1313. }
  1314. // TODO: "yield" where both key and value are inserted doesn't work
  1315. // [$find, $beforeToken, $extraLeft, $extraRight]
  1316. $this->insertionMap = [
  1317. 'Expr_ArrayDimFetch->dim' => ['[', false, null, null],
  1318. 'ArrayItem->key' => [null, false, null, ' => '],
  1319. 'Expr_ArrowFunction->returnType' => [')', false, ': ', null],
  1320. 'Expr_Closure->returnType' => [')', false, ': ', null],
  1321. 'Expr_Ternary->if' => ['?', false, ' ', ' '],
  1322. 'Expr_Yield->key' => [\T_YIELD, false, null, ' => '],
  1323. 'Expr_Yield->value' => [\T_YIELD, false, ' ', null],
  1324. 'Param->type' => [null, false, null, ' '],
  1325. 'Param->default' => [null, false, ' = ', null],
  1326. 'Stmt_Break->num' => [\T_BREAK, false, ' ', null],
  1327. 'Stmt_Catch->var' => [null, false, ' ', null],
  1328. 'Stmt_ClassMethod->returnType' => [')', false, ': ', null],
  1329. 'Stmt_ClassConst->type' => [\T_CONST, false, ' ', null],
  1330. 'Stmt_Class->extends' => [null, false, ' extends ', null],
  1331. 'Stmt_Enum->scalarType' => [null, false, ' : ', null],
  1332. 'Stmt_EnumCase->expr' => [null, false, ' = ', null],
  1333. 'Expr_PrintableNewAnonClass->extends' => [null, false, ' extends ', null],
  1334. 'Stmt_Continue->num' => [\T_CONTINUE, false, ' ', null],
  1335. 'Stmt_Foreach->keyVar' => [\T_AS, false, null, ' => '],
  1336. 'Stmt_Function->returnType' => [')', false, ': ', null],
  1337. 'Stmt_If->else' => [null, false, ' ', null],
  1338. 'Stmt_Namespace->name' => [\T_NAMESPACE, false, ' ', null],
  1339. 'Stmt_Property->type' => [\T_VARIABLE, true, null, ' '],
  1340. 'PropertyItem->default' => [null, false, ' = ', null],
  1341. 'Stmt_Return->expr' => [\T_RETURN, false, ' ', null],
  1342. 'Stmt_StaticVar->default' => [null, false, ' = ', null],
  1343. //'Stmt_TraitUseAdaptation_Alias->newName' => [T_AS, false, ' ', null], // TODO
  1344. 'Stmt_TryCatch->finally' => [null, false, ' ', null],
  1345. // 'Expr_Exit->expr': Complicated due to optional ()
  1346. // 'Stmt_Case->cond': Conversion from default to case
  1347. // 'Stmt_Class->name': Unclear
  1348. // 'Stmt_Declare->stmts': Not a proper node
  1349. // 'Stmt_TraitUseAdaptation_Alias->newModifier': Not a proper node
  1350. ];
  1351. }
  1352. protected function initializeListInsertionMap(): void {
  1353. if (isset($this->listInsertionMap)) {
  1354. return;
  1355. }
  1356. $this->listInsertionMap = [
  1357. // special
  1358. //'Expr_ShellExec->parts' => '', // TODO These need to be treated more carefully
  1359. //'Scalar_InterpolatedString->parts' => '',
  1360. Stmt\Catch_::class . '->types' => '|',
  1361. UnionType::class . '->types' => '|',
  1362. IntersectionType::class . '->types' => '&',
  1363. Stmt\If_::class . '->elseifs' => ' ',
  1364. Stmt\TryCatch::class . '->catches' => ' ',
  1365. // comma-separated lists
  1366. Expr\Array_::class . '->items' => ', ',
  1367. Expr\ArrowFunction::class . '->params' => ', ',
  1368. Expr\Closure::class . '->params' => ', ',
  1369. Expr\Closure::class . '->uses' => ', ',
  1370. Expr\FuncCall::class . '->args' => ', ',
  1371. Expr\Isset_::class . '->vars' => ', ',
  1372. Expr\List_::class . '->items' => ', ',
  1373. Expr\MethodCall::class . '->args' => ', ',
  1374. Expr\NullsafeMethodCall::class . '->args' => ', ',
  1375. Expr\New_::class . '->args' => ', ',
  1376. PrintableNewAnonClassNode::class . '->args' => ', ',
  1377. Expr\StaticCall::class . '->args' => ', ',
  1378. Stmt\ClassConst::class . '->consts' => ', ',
  1379. Stmt\ClassMethod::class . '->params' => ', ',
  1380. Stmt\Class_::class . '->implements' => ', ',
  1381. Stmt\Enum_::class . '->implements' => ', ',
  1382. PrintableNewAnonClassNode::class . '->implements' => ', ',
  1383. Stmt\Const_::class . '->consts' => ', ',
  1384. Stmt\Declare_::class . '->declares' => ', ',
  1385. Stmt\Echo_::class . '->exprs' => ', ',
  1386. Stmt\For_::class . '->init' => ', ',
  1387. Stmt\For_::class . '->cond' => ', ',
  1388. Stmt\For_::class . '->loop' => ', ',
  1389. Stmt\Function_::class . '->params' => ', ',
  1390. Stmt\Global_::class . '->vars' => ', ',
  1391. Stmt\GroupUse::class . '->uses' => ', ',
  1392. Stmt\Interface_::class . '->extends' => ', ',
  1393. Expr\Match_::class . '->arms' => ', ',
  1394. Stmt\Property::class . '->props' => ', ',
  1395. Stmt\StaticVar::class . '->vars' => ', ',
  1396. Stmt\TraitUse::class . '->traits' => ', ',
  1397. Stmt\TraitUseAdaptation\Precedence::class . '->insteadof' => ', ',
  1398. Stmt\Unset_::class . '->vars' => ', ',
  1399. Stmt\UseUse::class . '->uses' => ', ',
  1400. MatchArm::class . '->conds' => ', ',
  1401. AttributeGroup::class . '->attrs' => ', ',
  1402. PropertyHook::class . '->params' => ', ',
  1403. // statement lists
  1404. Expr\Closure::class . '->stmts' => "\n",
  1405. Stmt\Case_::class . '->stmts' => "\n",
  1406. Stmt\Catch_::class . '->stmts' => "\n",
  1407. Stmt\Class_::class . '->stmts' => "\n",
  1408. Stmt\Enum_::class . '->stmts' => "\n",
  1409. PrintableNewAnonClassNode::class . '->stmts' => "\n",
  1410. Stmt\Interface_::class . '->stmts' => "\n",
  1411. Stmt\Trait_::class . '->stmts' => "\n",
  1412. Stmt\ClassMethod::class . '->stmts' => "\n",
  1413. Stmt\Declare_::class . '->stmts' => "\n",
  1414. Stmt\Do_::class . '->stmts' => "\n",
  1415. Stmt\ElseIf_::class . '->stmts' => "\n",
  1416. Stmt\Else_::class . '->stmts' => "\n",
  1417. Stmt\Finally_::class . '->stmts' => "\n",
  1418. Stmt\Foreach_::class . '->stmts' => "\n",
  1419. Stmt\For_::class . '->stmts' => "\n",
  1420. Stmt\Function_::class . '->stmts' => "\n",
  1421. Stmt\If_::class . '->stmts' => "\n",
  1422. Stmt\Namespace_::class . '->stmts' => "\n",
  1423. Stmt\Block::class . '->stmts' => "\n",
  1424. // Attribute groups
  1425. Stmt\Class_::class . '->attrGroups' => "\n",
  1426. Stmt\Enum_::class . '->attrGroups' => "\n",
  1427. Stmt\EnumCase::class . '->attrGroups' => "\n",
  1428. Stmt\Interface_::class . '->attrGroups' => "\n",
  1429. Stmt\Trait_::class . '->attrGroups' => "\n",
  1430. Stmt\Function_::class . '->attrGroups' => "\n",
  1431. Stmt\ClassMethod::class . '->attrGroups' => "\n",
  1432. Stmt\ClassConst::class . '->attrGroups' => "\n",
  1433. Stmt\Property::class . '->attrGroups' => "\n",
  1434. PrintableNewAnonClassNode::class . '->attrGroups' => ' ',
  1435. Expr\Closure::class . '->attrGroups' => ' ',
  1436. Expr\ArrowFunction::class . '->attrGroups' => ' ',
  1437. Param::class . '->attrGroups' => ' ',
  1438. PropertyHook::class . '->attrGroups' => ' ',
  1439. Stmt\Switch_::class . '->cases' => "\n",
  1440. Stmt\TraitUse::class . '->adaptations' => "\n",
  1441. Stmt\TryCatch::class . '->stmts' => "\n",
  1442. Stmt\While_::class . '->stmts' => "\n",
  1443. PropertyHook::class . '->body' => "\n",
  1444. Stmt\Property::class . '->hooks' => "\n",
  1445. Param::class . '->hooks' => "\n",
  1446. // dummy for top-level context
  1447. 'File->stmts' => "\n",
  1448. ];
  1449. }
  1450. protected function initializeEmptyListInsertionMap(): void {
  1451. if (isset($this->emptyListInsertionMap)) {
  1452. return;
  1453. }
  1454. // TODO Insertion into empty statement lists.
  1455. // [$find, $extraLeft, $extraRight]
  1456. $this->emptyListInsertionMap = [
  1457. Expr\ArrowFunction::class . '->params' => ['(', '', ''],
  1458. Expr\Closure::class . '->uses' => [')', ' use (', ')'],
  1459. Expr\Closure::class . '->params' => ['(', '', ''],
  1460. Expr\FuncCall::class . '->args' => ['(', '', ''],
  1461. Expr\MethodCall::class . '->args' => ['(', '', ''],
  1462. Expr\NullsafeMethodCall::class . '->args' => ['(', '', ''],
  1463. Expr\New_::class . '->args' => ['(', '', ''],
  1464. PrintableNewAnonClassNode::class . '->args' => ['(', '', ''],
  1465. PrintableNewAnonClassNode::class . '->implements' => [null, ' implements ', ''],
  1466. Expr\StaticCall::class . '->args' => ['(', '', ''],
  1467. Stmt\Class_::class . '->implements' => [null, ' implements ', ''],
  1468. Stmt\Enum_::class . '->implements' => [null, ' implements ', ''],
  1469. Stmt\ClassMethod::class . '->params' => ['(', '', ''],
  1470. Stmt\Interface_::class . '->extends' => [null, ' extends ', ''],
  1471. Stmt\Function_::class . '->params' => ['(', '', ''],
  1472. Stmt\Interface_::class . '->attrGroups' => [null, '', "\n"],
  1473. Stmt\Class_::class . '->attrGroups' => [null, '', "\n"],
  1474. Stmt\ClassConst::class . '->attrGroups' => [null, '', "\n"],
  1475. Stmt\ClassMethod::class . '->attrGroups' => [null, '', "\n"],
  1476. Stmt\Function_::class . '->attrGroups' => [null, '', "\n"],
  1477. Stmt\Property::class . '->attrGroups' => [null, '', "\n"],
  1478. Stmt\Trait_::class . '->attrGroups' => [null, '', "\n"],
  1479. Expr\ArrowFunction::class . '->attrGroups' => [null, '', ' '],
  1480. Expr\Closure::class . '->attrGroups' => [null, '', ' '],
  1481. PrintableNewAnonClassNode::class . '->attrGroups' => [\T_NEW, ' ', ''],
  1482. /* These cannot be empty to start with:
  1483. * Expr_Isset->vars
  1484. * Stmt_Catch->types
  1485. * Stmt_Const->consts
  1486. * Stmt_ClassConst->consts
  1487. * Stmt_Declare->declares
  1488. * Stmt_Echo->exprs
  1489. * Stmt_Global->vars
  1490. * Stmt_GroupUse->uses
  1491. * Stmt_Property->props
  1492. * Stmt_StaticVar->vars
  1493. * Stmt_TraitUse->traits
  1494. * Stmt_TraitUseAdaptation_Precedence->insteadof
  1495. * Stmt_Unset->vars
  1496. * Stmt_Use->uses
  1497. * UnionType->types
  1498. */
  1499. /* TODO
  1500. * Stmt_If->elseifs
  1501. * Stmt_TryCatch->catches
  1502. * Expr_Array->items
  1503. * Expr_List->items
  1504. * Stmt_For->init
  1505. * Stmt_For->cond
  1506. * Stmt_For->loop
  1507. */
  1508. ];
  1509. }
  1510. protected function initializeModifierChangeMap(): void {
  1511. if (isset($this->modifierChangeMap)) {
  1512. return;
  1513. }
  1514. $this->modifierChangeMap = [
  1515. Stmt\ClassConst::class . '->flags' => ['pModifiers', \T_CONST],
  1516. Stmt\ClassMethod::class . '->flags' => ['pModifiers', \T_FUNCTION],
  1517. Stmt\Class_::class . '->flags' => ['pModifiers', \T_CLASS],
  1518. Stmt\Property::class . '->flags' => ['pModifiers', \T_VARIABLE],
  1519. PrintableNewAnonClassNode::class . '->flags' => ['pModifiers', \T_CLASS],
  1520. Param::class . '->flags' => ['pModifiers', \T_VARIABLE],
  1521. PropertyHook::class . '->flags' => ['pModifiers', \T_STRING],
  1522. Expr\Closure::class . '->static' => ['pStatic', \T_FUNCTION],
  1523. Expr\ArrowFunction::class . '->static' => ['pStatic', \T_FN],
  1524. //Stmt\TraitUseAdaptation\Alias::class . '->newModifier' => 0, // TODO
  1525. ];
  1526. // List of integer subnodes that are not modifiers:
  1527. // Expr_Include->type
  1528. // Stmt_GroupUse->type
  1529. // Stmt_Use->type
  1530. // UseItem->type
  1531. }
  1532. }