PrettyPrinterAbstract.php 71 KB

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