PrettyPrinterAbstract.php 71 KB

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