PrettyPrinterAbstract.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. namespace PhpParser;
  3. use PhpParser\Node\Expr;
  4. use PhpParser\Node\Stmt;
  5. abstract class PrettyPrinterAbstract
  6. {
  7. protected $precedenceMap = array(
  8. // [precedence, associativity] where for the latter -1 is %left, 0 is %nonassoc and 1 is %right
  9. 'Expr_BinaryOp_Pow' => array( 0, 1),
  10. 'Expr_BitwiseNot' => array( 10, 1),
  11. 'Expr_PreInc' => array( 10, 1),
  12. 'Expr_PreDec' => array( 10, 1),
  13. 'Expr_PostInc' => array( 10, -1),
  14. 'Expr_PostDec' => array( 10, -1),
  15. 'Expr_UnaryPlus' => array( 10, 1),
  16. 'Expr_UnaryMinus' => array( 10, 1),
  17. 'Expr_Cast_Int' => array( 10, 1),
  18. 'Expr_Cast_Double' => array( 10, 1),
  19. 'Expr_Cast_String' => array( 10, 1),
  20. 'Expr_Cast_Array' => array( 10, 1),
  21. 'Expr_Cast_Object' => array( 10, 1),
  22. 'Expr_Cast_Bool' => array( 10, 1),
  23. 'Expr_Cast_Unset' => array( 10, 1),
  24. 'Expr_ErrorSuppress' => array( 10, 1),
  25. 'Expr_Instanceof' => array( 20, 0),
  26. 'Expr_BooleanNot' => array( 30, 1),
  27. 'Expr_BinaryOp_Mul' => array( 40, -1),
  28. 'Expr_BinaryOp_Div' => array( 40, -1),
  29. 'Expr_BinaryOp_Mod' => array( 40, -1),
  30. 'Expr_BinaryOp_Plus' => array( 50, -1),
  31. 'Expr_BinaryOp_Minus' => array( 50, -1),
  32. 'Expr_BinaryOp_Concat' => array( 50, -1),
  33. 'Expr_BinaryOp_ShiftLeft' => array( 60, -1),
  34. 'Expr_BinaryOp_ShiftRight' => array( 60, -1),
  35. 'Expr_BinaryOp_Smaller' => array( 70, 0),
  36. 'Expr_BinaryOp_SmallerOrEqual' => array( 70, 0),
  37. 'Expr_BinaryOp_Greater' => array( 70, 0),
  38. 'Expr_BinaryOp_GreaterOrEqual' => array( 70, 0),
  39. 'Expr_BinaryOp_Equal' => array( 80, 0),
  40. 'Expr_BinaryOp_NotEqual' => array( 80, 0),
  41. 'Expr_BinaryOp_Identical' => array( 80, 0),
  42. 'Expr_BinaryOp_NotIdentical' => array( 80, 0),
  43. 'Expr_BinaryOp_Spaceship' => array( 80, 0),
  44. 'Expr_BinaryOp_BitwiseAnd' => array( 90, -1),
  45. 'Expr_BinaryOp_BitwiseXor' => array(100, -1),
  46. 'Expr_BinaryOp_BitwiseOr' => array(110, -1),
  47. 'Expr_BinaryOp_BooleanAnd' => array(120, -1),
  48. 'Expr_BinaryOp_BooleanOr' => array(130, -1),
  49. 'Expr_BinaryOp_Coalesce' => array(140, 1),
  50. 'Expr_Ternary' => array(150, -1),
  51. // parser uses %left for assignments, but they really behave as %right
  52. 'Expr_Assign' => array(160, 1),
  53. 'Expr_AssignRef' => array(160, 1),
  54. 'Expr_AssignOp_Plus' => array(160, 1),
  55. 'Expr_AssignOp_Minus' => array(160, 1),
  56. 'Expr_AssignOp_Mul' => array(160, 1),
  57. 'Expr_AssignOp_Div' => array(160, 1),
  58. 'Expr_AssignOp_Concat' => array(160, 1),
  59. 'Expr_AssignOp_Mod' => array(160, 1),
  60. 'Expr_AssignOp_BitwiseAnd' => array(160, 1),
  61. 'Expr_AssignOp_BitwiseOr' => array(160, 1),
  62. 'Expr_AssignOp_BitwiseXor' => array(160, 1),
  63. 'Expr_AssignOp_ShiftLeft' => array(160, 1),
  64. 'Expr_AssignOp_ShiftRight' => array(160, 1),
  65. 'Expr_AssignOp_Pow' => array(160, 1),
  66. 'Expr_YieldFrom' => array(165, 1),
  67. 'Expr_Print' => array(168, 1),
  68. 'Expr_BinaryOp_LogicalAnd' => array(170, -1),
  69. 'Expr_BinaryOp_LogicalXor' => array(180, -1),
  70. 'Expr_BinaryOp_LogicalOr' => array(190, -1),
  71. 'Expr_Include' => array(200, -1),
  72. );
  73. protected $noIndentToken;
  74. protected $docStringEndToken;
  75. protected $canUseSemicolonNamespaces;
  76. protected $options;
  77. /**
  78. * Creates a pretty printer instance using the given options.
  79. *
  80. * Supported options:
  81. * * bool $shortArraySyntax = false: Whether to use [] instead of array() as the default array
  82. * syntax, if the node does not specify a format.
  83. *
  84. * @param array $options Dictionary of formatting options
  85. */
  86. public function __construct(array $options = []) {
  87. $this->noIndentToken = '_NO_INDENT_' . mt_rand();
  88. $this->docStringEndToken = '_DOC_STRING_END_' . mt_rand();
  89. $defaultOptions = ['shortArraySyntax' => false];
  90. $this->options = $options + $defaultOptions;
  91. }
  92. /**
  93. * Pretty prints an array of statements.
  94. *
  95. * @param Node[] $stmts Array of statements
  96. *
  97. * @return string Pretty printed statements
  98. */
  99. public function prettyPrint(array $stmts) {
  100. $this->preprocessNodes($stmts);
  101. return ltrim($this->handleMagicTokens($this->pStmts($stmts, false)));
  102. }
  103. /**
  104. * Pretty prints an expression.
  105. *
  106. * @param Expr $node Expression node
  107. *
  108. * @return string Pretty printed node
  109. */
  110. public function prettyPrintExpr(Expr $node) {
  111. return $this->handleMagicTokens($this->p($node));
  112. }
  113. /**
  114. * Pretty prints a file of statements (includes the opening <?php tag if it is required).
  115. *
  116. * @param Node[] $stmts Array of statements
  117. *
  118. * @return string Pretty printed statements
  119. */
  120. public function prettyPrintFile(array $stmts) {
  121. if (!$stmts) {
  122. return "<?php\n\n";
  123. }
  124. $p = "<?php\n\n" . $this->prettyPrint($stmts);
  125. if ($stmts[0] instanceof Stmt\InlineHTML) {
  126. $p = preg_replace('/^<\?php\s+\?>\n?/', '', $p);
  127. }
  128. if ($stmts[count($stmts) - 1] instanceof Stmt\InlineHTML) {
  129. $p = preg_replace('/<\?php$/', '', rtrim($p));
  130. }
  131. return $p;
  132. }
  133. /**
  134. * Preprocesses the top-level nodes to initialize pretty printer state.
  135. *
  136. * @param Node[] $nodes Array of nodes
  137. */
  138. protected function preprocessNodes(array $nodes) {
  139. /* We can use semicolon-namespaces unless there is a global namespace declaration */
  140. $this->canUseSemicolonNamespaces = true;
  141. foreach ($nodes as $node) {
  142. if ($node instanceof Stmt\Namespace_ && null === $node->name) {
  143. $this->canUseSemicolonNamespaces = false;
  144. }
  145. }
  146. }
  147. protected function handleMagicTokens($str) {
  148. // Drop no-indent tokens
  149. $str = str_replace($this->noIndentToken, '', $str);
  150. // Replace doc-string-end tokens with nothing or a newline
  151. $str = str_replace($this->docStringEndToken . ";\n", ";\n", $str);
  152. $str = str_replace($this->docStringEndToken, "\n", $str);
  153. return $str;
  154. }
  155. /**
  156. * Pretty prints an array of nodes (statements) and indents them optionally.
  157. *
  158. * @param Node[] $nodes Array of nodes
  159. * @param bool $indent Whether to indent the printed nodes
  160. *
  161. * @return string Pretty printed statements
  162. */
  163. protected function pStmts(array $nodes, $indent = true) {
  164. $result = '';
  165. foreach ($nodes as $node) {
  166. $comments = $node->getAttribute('comments', array());
  167. if ($comments) {
  168. $result .= "\n" . $this->pComments($comments);
  169. if ($node instanceof Stmt\Nop) {
  170. continue;
  171. }
  172. }
  173. $result .= "\n" . $this->p($node) . ($node instanceof Expr ? ';' : '');
  174. }
  175. if ($indent) {
  176. return preg_replace('~\n(?!$|' . $this->noIndentToken . ')~', "\n ", $result);
  177. } else {
  178. return $result;
  179. }
  180. }
  181. /**
  182. * Pretty prints a node.
  183. *
  184. * @param Node $node Node to be pretty printed
  185. *
  186. * @return string Pretty printed node
  187. */
  188. protected function p(Node $node) {
  189. return $this->{'p' . $node->getType()}($node);
  190. }
  191. protected function pInfixOp($type, Node $leftNode, $operatorString, Node $rightNode) {
  192. list($precedence, $associativity) = $this->precedenceMap[$type];
  193. return $this->pPrec($leftNode, $precedence, $associativity, -1)
  194. . $operatorString
  195. . $this->pPrec($rightNode, $precedence, $associativity, 1);
  196. }
  197. protected function pPrefixOp($type, $operatorString, Node $node) {
  198. list($precedence, $associativity) = $this->precedenceMap[$type];
  199. return $operatorString . $this->pPrec($node, $precedence, $associativity, 1);
  200. }
  201. protected function pPostfixOp($type, Node $node, $operatorString) {
  202. list($precedence, $associativity) = $this->precedenceMap[$type];
  203. return $this->pPrec($node, $precedence, $associativity, -1) . $operatorString;
  204. }
  205. /**
  206. * Prints an expression node with the least amount of parentheses necessary to preserve the meaning.
  207. *
  208. * @param Node $node Node to pretty print
  209. * @param int $parentPrecedence Precedence of the parent operator
  210. * @param int $parentAssociativity Associativity of parent operator
  211. * (-1 is left, 0 is nonassoc, 1 is right)
  212. * @param int $childPosition Position of the node relative to the operator
  213. * (-1 is left, 1 is right)
  214. *
  215. * @return string The pretty printed node
  216. */
  217. protected function pPrec(Node $node, $parentPrecedence, $parentAssociativity, $childPosition) {
  218. $type = $node->getType();
  219. if (isset($this->precedenceMap[$type])) {
  220. $childPrecedence = $this->precedenceMap[$type][0];
  221. if ($childPrecedence > $parentPrecedence
  222. || ($parentPrecedence == $childPrecedence && $parentAssociativity != $childPosition)
  223. ) {
  224. return '(' . $this->p($node) . ')';
  225. }
  226. }
  227. return $this->p($node);
  228. }
  229. /**
  230. * Pretty prints an array of nodes and implodes the printed values.
  231. *
  232. * @param Node[] $nodes Array of Nodes to be printed
  233. * @param string $glue Character to implode with
  234. *
  235. * @return string Imploded pretty printed nodes
  236. */
  237. protected function pImplode(array $nodes, $glue = '') {
  238. $pNodes = array();
  239. foreach ($nodes as $node) {
  240. if (null === $node) {
  241. $pNodes[] = '';
  242. } else {
  243. $pNodes[] = $this->p($node);
  244. }
  245. }
  246. return implode($glue, $pNodes);
  247. }
  248. /**
  249. * Pretty prints an array of nodes and implodes the printed values with commas.
  250. *
  251. * @param Node[] $nodes Array of Nodes to be printed
  252. *
  253. * @return string Comma separated pretty printed nodes
  254. */
  255. protected function pCommaSeparated(array $nodes) {
  256. return $this->pImplode($nodes, ', ');
  257. }
  258. /**
  259. * Signals the pretty printer that a string shall not be indented.
  260. *
  261. * @param string $string Not to be indented string
  262. *
  263. * @return string String marked with $this->noIndentToken's.
  264. */
  265. protected function pNoIndent($string) {
  266. return str_replace("\n", "\n" . $this->noIndentToken, $string);
  267. }
  268. /**
  269. * Prints reformatted text of the passed comments.
  270. *
  271. * @param Comment[] $comments List of comments
  272. *
  273. * @return string Reformatted text of comments
  274. */
  275. protected function pComments(array $comments) {
  276. $formattedComments = [];
  277. foreach ($comments as $comment) {
  278. $formattedComments[] = $comment->getReformattedText();
  279. }
  280. return implode("\n", $formattedComments);
  281. }
  282. }