PrettyPrinterAbstract.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 $canUseSemicolonNamespaces;
  75. public function __construct() {
  76. $this->noIndentToken = '_NO_INDENT_' . mt_rand();
  77. }
  78. /**
  79. * Pretty prints an array of statements.
  80. *
  81. * @param Node[] $stmts Array of statements
  82. *
  83. * @return string Pretty printed statements
  84. */
  85. public function prettyPrint(array $stmts) {
  86. $this->preprocessNodes($stmts);
  87. return ltrim(str_replace("\n" . $this->noIndentToken, "\n", $this->pStmts($stmts, false)));
  88. }
  89. /**
  90. * Pretty prints an expression.
  91. *
  92. * @param Expr $node Expression node
  93. *
  94. * @return string Pretty printed node
  95. */
  96. public function prettyPrintExpr(Expr $node) {
  97. return str_replace("\n" . $this->noIndentToken, "\n", $this->p($node));
  98. }
  99. /**
  100. * Pretty prints a file of statements (includes the opening <?php tag if it is required).
  101. *
  102. * @param Node[] $stmts Array of statements
  103. *
  104. * @return string Pretty printed statements
  105. */
  106. public function prettyPrintFile(array $stmts) {
  107. $p = rtrim($this->prettyPrint($stmts));
  108. $p = preg_replace('/^\?>\n?/', '', $p, -1, $count);
  109. $p = preg_replace('/<\?php$/', '', $p);
  110. if (!$count) {
  111. $p = "<?php\n\n" . $p;
  112. }
  113. return $p;
  114. }
  115. /**
  116. * Preprocesses the top-level nodes to initialize pretty printer state.
  117. *
  118. * @param Node[] $nodes Array of nodes
  119. */
  120. protected function preprocessNodes(array $nodes) {
  121. /* We can use semicolon-namespaces unless there is a global namespace declaration */
  122. $this->canUseSemicolonNamespaces = true;
  123. foreach ($nodes as $node) {
  124. if ($node instanceof Stmt\Namespace_ && null === $node->name) {
  125. $this->canUseSemicolonNamespaces = false;
  126. }
  127. }
  128. }
  129. /**
  130. * Pretty prints an array of nodes (statements) and indents them optionally.
  131. *
  132. * @param Node[] $nodes Array of nodes
  133. * @param bool $indent Whether to indent the printed nodes
  134. *
  135. * @return string Pretty printed statements
  136. */
  137. protected function pStmts(array $nodes, $indent = true) {
  138. $result = '';
  139. foreach ($nodes as $node) {
  140. $result .= "\n"
  141. . $this->pComments($node->getAttribute('comments', array()))
  142. . $this->p($node)
  143. . ($node instanceof Expr ? ';' : '');
  144. }
  145. if ($indent) {
  146. return preg_replace('~\n(?!$|' . $this->noIndentToken . ')~', "\n ", $result);
  147. } else {
  148. return $result;
  149. }
  150. }
  151. /**
  152. * Pretty prints a node.
  153. *
  154. * @param Node $node Node to be pretty printed
  155. *
  156. * @return string Pretty printed node
  157. */
  158. protected function p(Node $node) {
  159. return $this->{'p' . $node->getType()}($node);
  160. }
  161. protected function pInfixOp($type, Node $leftNode, $operatorString, Node $rightNode) {
  162. list($precedence, $associativity) = $this->precedenceMap[$type];
  163. return $this->pPrec($leftNode, $precedence, $associativity, -1)
  164. . $operatorString
  165. . $this->pPrec($rightNode, $precedence, $associativity, 1);
  166. }
  167. protected function pPrefixOp($type, $operatorString, Node $node) {
  168. list($precedence, $associativity) = $this->precedenceMap[$type];
  169. return $operatorString . $this->pPrec($node, $precedence, $associativity, 1);
  170. }
  171. protected function pPostfixOp($type, Node $node, $operatorString) {
  172. list($precedence, $associativity) = $this->precedenceMap[$type];
  173. return $this->pPrec($node, $precedence, $associativity, -1) . $operatorString;
  174. }
  175. /**
  176. * Prints an expression node with the least amount of parentheses necessary to preserve the meaning.
  177. *
  178. * @param Node $node Node to pretty print
  179. * @param int $parentPrecedence Precedence of the parent operator
  180. * @param int $parentAssociativity Associativity of parent operator
  181. * (-1 is left, 0 is nonassoc, 1 is right)
  182. * @param int $childPosition Position of the node relative to the operator
  183. * (-1 is left, 1 is right)
  184. *
  185. * @return string The pretty printed node
  186. */
  187. protected function pPrec(Node $node, $parentPrecedence, $parentAssociativity, $childPosition) {
  188. $type = $node->getType();
  189. if (isset($this->precedenceMap[$type])) {
  190. $childPrecedence = $this->precedenceMap[$type][0];
  191. if ($childPrecedence > $parentPrecedence
  192. || ($parentPrecedence == $childPrecedence && $parentAssociativity != $childPosition)
  193. ) {
  194. return '(' . $this->{'p' . $type}($node) . ')';
  195. }
  196. }
  197. return $this->{'p' . $type}($node);
  198. }
  199. /**
  200. * Pretty prints an array of nodes and implodes the printed values.
  201. *
  202. * @param Node[] $nodes Array of Nodes to be printed
  203. * @param string $glue Character to implode with
  204. *
  205. * @return string Imploded pretty printed nodes
  206. */
  207. protected function pImplode(array $nodes, $glue = '') {
  208. $pNodes = array();
  209. foreach ($nodes as $node) {
  210. $pNodes[] = $this->p($node);
  211. }
  212. return implode($glue, $pNodes);
  213. }
  214. /**
  215. * Pretty prints an array of nodes and implodes the printed values with commas.
  216. *
  217. * @param Node[] $nodes Array of Nodes to be printed
  218. *
  219. * @return string Comma separated pretty printed nodes
  220. */
  221. protected function pCommaSeparated(array $nodes) {
  222. return $this->pImplode($nodes, ', ');
  223. }
  224. /**
  225. * Signals the pretty printer that a string shall not be indented.
  226. *
  227. * @param string $string Not to be indented string
  228. *
  229. * @return mixed String marked with $this->noIndentToken's.
  230. */
  231. protected function pNoIndent($string) {
  232. return str_replace("\n", "\n" . $this->noIndentToken, $string);
  233. }
  234. protected function pComments(array $comments) {
  235. $result = '';
  236. foreach ($comments as $comment) {
  237. $result .= $comment->getReformattedText() . "\n";
  238. }
  239. return $result;
  240. }
  241. }