PrettyPrinterAbstract.php 68 KB

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