Standard.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\PrettyPrinter;
  3. use PhpParser\Node;
  4. use PhpParser\Node\Expr;
  5. use PhpParser\Node\Expr\AssignOp;
  6. use PhpParser\Node\Expr\BinaryOp;
  7. use PhpParser\Node\Expr\Cast;
  8. use PhpParser\Node\Name;
  9. use PhpParser\Node\Scalar;
  10. use PhpParser\Node\Scalar\MagicConst;
  11. use PhpParser\Node\Stmt;
  12. use PhpParser\PrettyPrinterAbstract;
  13. class Standard extends PrettyPrinterAbstract
  14. {
  15. // Special nodes
  16. protected function pParam(Node\Param $node) {
  17. return ($node->type ? $this->p($node->type) . ' ' : '')
  18. . ($node->byRef ? '&' : '')
  19. . ($node->variadic ? '...' : '')
  20. . $this->p($node->var)
  21. . ($node->default ? ' = ' . $this->p($node->default) : '');
  22. }
  23. protected function pArg(Node\Arg $node) {
  24. return ($node->byRef ? '&' : '') . ($node->unpack ? '...' : '') . $this->p($node->value);
  25. }
  26. protected function pConst(Node\Const_ $node) {
  27. return $node->name . ' = ' . $this->p($node->value);
  28. }
  29. protected function pNullableType(Node\NullableType $node) {
  30. return '?' . $this->p($node->type);
  31. }
  32. protected function pIdentifier(Node\Identifier $node) {
  33. return $node->name;
  34. }
  35. protected function pVarLikeIdentifier(Node\VarLikeIdentifier $node) {
  36. return '$' . $node->name;
  37. }
  38. // Names
  39. protected function pName(Name $node) {
  40. return implode('\\', $node->parts);
  41. }
  42. protected function pName_FullyQualified(Name\FullyQualified $node) {
  43. return '\\' . implode('\\', $node->parts);
  44. }
  45. protected function pName_Relative(Name\Relative $node) {
  46. return 'namespace\\' . implode('\\', $node->parts);
  47. }
  48. // Magic Constants
  49. protected function pScalar_MagicConst_Class(MagicConst\Class_ $node) {
  50. return '__CLASS__';
  51. }
  52. protected function pScalar_MagicConst_Dir(MagicConst\Dir $node) {
  53. return '__DIR__';
  54. }
  55. protected function pScalar_MagicConst_File(MagicConst\File $node) {
  56. return '__FILE__';
  57. }
  58. protected function pScalar_MagicConst_Function(MagicConst\Function_ $node) {
  59. return '__FUNCTION__';
  60. }
  61. protected function pScalar_MagicConst_Line(MagicConst\Line $node) {
  62. return '__LINE__';
  63. }
  64. protected function pScalar_MagicConst_Method(MagicConst\Method $node) {
  65. return '__METHOD__';
  66. }
  67. protected function pScalar_MagicConst_Namespace(MagicConst\Namespace_ $node) {
  68. return '__NAMESPACE__';
  69. }
  70. protected function pScalar_MagicConst_Trait(MagicConst\Trait_ $node) {
  71. return '__TRAIT__';
  72. }
  73. // Scalars
  74. protected function pScalar_String(Scalar\String_ $node) {
  75. $kind = $node->getAttribute('kind', Scalar\String_::KIND_SINGLE_QUOTED);
  76. switch ($kind) {
  77. case Scalar\String_::KIND_NOWDOC:
  78. $label = $node->getAttribute('docLabel');
  79. if ($label && !$this->containsEndLabel($node->value, $label)) {
  80. if ($node->value === '') {
  81. return "<<<'$label'\n$label" . $this->docStringEndToken;
  82. }
  83. return "<<<'$label'\n$node->value\n$label"
  84. . $this->docStringEndToken;
  85. }
  86. /* break missing intentionally */
  87. case Scalar\String_::KIND_SINGLE_QUOTED:
  88. return $this->pSingleQuotedString($node->value);
  89. case Scalar\String_::KIND_HEREDOC:
  90. $label = $node->getAttribute('docLabel');
  91. if ($label && !$this->containsEndLabel($node->value, $label)) {
  92. if ($node->value === '') {
  93. return "<<<$label\n$label" . $this->docStringEndToken;
  94. }
  95. $escaped = $this->escapeString($node->value, null);
  96. return "<<<$label\n" . $escaped . "\n$label"
  97. . $this->docStringEndToken;
  98. }
  99. /* break missing intentionally */
  100. case Scalar\String_::KIND_DOUBLE_QUOTED:
  101. return '"' . $this->escapeString($node->value, '"') . '"';
  102. }
  103. throw new \Exception('Invalid string kind');
  104. }
  105. protected function pScalar_Encapsed(Scalar\Encapsed $node) {
  106. if ($node->getAttribute('kind') === Scalar\String_::KIND_HEREDOC) {
  107. $label = $node->getAttribute('docLabel');
  108. if ($label && !$this->encapsedContainsEndLabel($node->parts, $label)) {
  109. if (count($node->parts) === 1
  110. && $node->parts[0] instanceof Scalar\EncapsedStringPart
  111. && $node->parts[0]->value === ''
  112. ) {
  113. return "<<<$label\n$label" . $this->docStringEndToken;
  114. }
  115. return "<<<$label\n" . $this->pEncapsList($node->parts, null) . "\n$label"
  116. . $this->docStringEndToken;
  117. }
  118. }
  119. return '"' . $this->pEncapsList($node->parts, '"') . '"';
  120. }
  121. protected function pScalar_LNumber(Scalar\LNumber $node) {
  122. if ($node->value === -\PHP_INT_MAX-1) {
  123. // PHP_INT_MIN cannot be represented as a literal,
  124. // because the sign is not part of the literal
  125. return '(-' . \PHP_INT_MAX . '-1)';
  126. }
  127. $kind = $node->getAttribute('kind', Scalar\LNumber::KIND_DEC);
  128. if (Scalar\LNumber::KIND_DEC === $kind) {
  129. return (string) $node->value;
  130. }
  131. $sign = $node->value < 0 ? '-' : '';
  132. $str = (string) $node->value;
  133. switch ($kind) {
  134. case Scalar\LNumber::KIND_BIN:
  135. return $sign . '0b' . base_convert($str, 10, 2);
  136. case Scalar\LNumber::KIND_OCT:
  137. return $sign . '0' . base_convert($str, 10, 8);
  138. case Scalar\LNumber::KIND_HEX:
  139. return $sign . '0x' . base_convert($str, 10, 16);
  140. }
  141. throw new \Exception('Invalid number kind');
  142. }
  143. protected function pScalar_DNumber(Scalar\DNumber $node) {
  144. if (!is_finite($node->value)) {
  145. if ($node->value === \INF) {
  146. return '\INF';
  147. } elseif ($node->value === -\INF) {
  148. return '-\INF';
  149. } else {
  150. return '\NAN';
  151. }
  152. }
  153. // Try to find a short full-precision representation
  154. $stringValue = sprintf('%.16G', $node->value);
  155. if ($node->value !== (double) $stringValue) {
  156. $stringValue = sprintf('%.17G', $node->value);
  157. }
  158. // %G is locale dependent and there exists no locale-independent alternative. We don't want
  159. // mess with switching locales here, so let's assume that a comma is the only non-standard
  160. // decimal separator we may encounter...
  161. $stringValue = str_replace(',', '.', $stringValue);
  162. // ensure that number is really printed as float
  163. return preg_match('/^-?[0-9]+$/', $stringValue) ? $stringValue . '.0' : $stringValue;
  164. }
  165. protected function pScalar_EncapsedStringPart(Scalar\EncapsedStringPart $node) {
  166. throw new \LogicException('Cannot directly print EncapsedStringPart');
  167. }
  168. // Assignments
  169. protected function pExpr_Assign(Expr\Assign $node) {
  170. return $this->pInfixOp(Expr\Assign::class, $node->var, ' = ', $node->expr);
  171. }
  172. protected function pExpr_AssignRef(Expr\AssignRef $node) {
  173. return $this->pInfixOp(Expr\AssignRef::class, $node->var, ' =& ', $node->expr);
  174. }
  175. protected function pExpr_AssignOp_Plus(AssignOp\Plus $node) {
  176. return $this->pInfixOp(AssignOp\Plus::class, $node->var, ' += ', $node->expr);
  177. }
  178. protected function pExpr_AssignOp_Minus(AssignOp\Minus $node) {
  179. return $this->pInfixOp(AssignOp\Minus::class, $node->var, ' -= ', $node->expr);
  180. }
  181. protected function pExpr_AssignOp_Mul(AssignOp\Mul $node) {
  182. return $this->pInfixOp(AssignOp\Mul::class, $node->var, ' *= ', $node->expr);
  183. }
  184. protected function pExpr_AssignOp_Div(AssignOp\Div $node) {
  185. return $this->pInfixOp(AssignOp\Div::class, $node->var, ' /= ', $node->expr);
  186. }
  187. protected function pExpr_AssignOp_Concat(AssignOp\Concat $node) {
  188. return $this->pInfixOp(AssignOp\Concat::class, $node->var, ' .= ', $node->expr);
  189. }
  190. protected function pExpr_AssignOp_Mod(AssignOp\Mod $node) {
  191. return $this->pInfixOp(AssignOp\Mod::class, $node->var, ' %= ', $node->expr);
  192. }
  193. protected function pExpr_AssignOp_BitwiseAnd(AssignOp\BitwiseAnd $node) {
  194. return $this->pInfixOp(AssignOp\BitwiseAnd::class, $node->var, ' &= ', $node->expr);
  195. }
  196. protected function pExpr_AssignOp_BitwiseOr(AssignOp\BitwiseOr $node) {
  197. return $this->pInfixOp(AssignOp\BitwiseOr::class, $node->var, ' |= ', $node->expr);
  198. }
  199. protected function pExpr_AssignOp_BitwiseXor(AssignOp\BitwiseXor $node) {
  200. return $this->pInfixOp(AssignOp\BitwiseXor::class, $node->var, ' ^= ', $node->expr);
  201. }
  202. protected function pExpr_AssignOp_ShiftLeft(AssignOp\ShiftLeft $node) {
  203. return $this->pInfixOp(AssignOp\ShiftLeft::class, $node->var, ' <<= ', $node->expr);
  204. }
  205. protected function pExpr_AssignOp_ShiftRight(AssignOp\ShiftRight $node) {
  206. return $this->pInfixOp(AssignOp\ShiftRight::class, $node->var, ' >>= ', $node->expr);
  207. }
  208. protected function pExpr_AssignOp_Pow(AssignOp\Pow $node) {
  209. return $this->pInfixOp(AssignOp\Pow::class, $node->var, ' **= ', $node->expr);
  210. }
  211. protected function pExpr_AssignOp_Coalesce(AssignOp\Coalesce $node) {
  212. return $this->pInfixOp(AssignOp\Coalesce::class, $node->var, ' ??= ', $node->expr);
  213. }
  214. // Binary expressions
  215. protected function pExpr_BinaryOp_Plus(BinaryOp\Plus $node) {
  216. return $this->pInfixOp(BinaryOp\Plus::class, $node->left, ' + ', $node->right);
  217. }
  218. protected function pExpr_BinaryOp_Minus(BinaryOp\Minus $node) {
  219. return $this->pInfixOp(BinaryOp\Minus::class, $node->left, ' - ', $node->right);
  220. }
  221. protected function pExpr_BinaryOp_Mul(BinaryOp\Mul $node) {
  222. return $this->pInfixOp(BinaryOp\Mul::class, $node->left, ' * ', $node->right);
  223. }
  224. protected function pExpr_BinaryOp_Div(BinaryOp\Div $node) {
  225. return $this->pInfixOp(BinaryOp\Div::class, $node->left, ' / ', $node->right);
  226. }
  227. protected function pExpr_BinaryOp_Concat(BinaryOp\Concat $node) {
  228. return $this->pInfixOp(BinaryOp\Concat::class, $node->left, ' . ', $node->right);
  229. }
  230. protected function pExpr_BinaryOp_Mod(BinaryOp\Mod $node) {
  231. return $this->pInfixOp(BinaryOp\Mod::class, $node->left, ' % ', $node->right);
  232. }
  233. protected function pExpr_BinaryOp_BooleanAnd(BinaryOp\BooleanAnd $node) {
  234. return $this->pInfixOp(BinaryOp\BooleanAnd::class, $node->left, ' && ', $node->right);
  235. }
  236. protected function pExpr_BinaryOp_BooleanOr(BinaryOp\BooleanOr $node) {
  237. return $this->pInfixOp(BinaryOp\BooleanOr::class, $node->left, ' || ', $node->right);
  238. }
  239. protected function pExpr_BinaryOp_BitwiseAnd(BinaryOp\BitwiseAnd $node) {
  240. return $this->pInfixOp(BinaryOp\BitwiseAnd::class, $node->left, ' & ', $node->right);
  241. }
  242. protected function pExpr_BinaryOp_BitwiseOr(BinaryOp\BitwiseOr $node) {
  243. return $this->pInfixOp(BinaryOp\BitwiseOr::class, $node->left, ' | ', $node->right);
  244. }
  245. protected function pExpr_BinaryOp_BitwiseXor(BinaryOp\BitwiseXor $node) {
  246. return $this->pInfixOp(BinaryOp\BitwiseXor::class, $node->left, ' ^ ', $node->right);
  247. }
  248. protected function pExpr_BinaryOp_ShiftLeft(BinaryOp\ShiftLeft $node) {
  249. return $this->pInfixOp(BinaryOp\ShiftLeft::class, $node->left, ' << ', $node->right);
  250. }
  251. protected function pExpr_BinaryOp_ShiftRight(BinaryOp\ShiftRight $node) {
  252. return $this->pInfixOp(BinaryOp\ShiftRight::class, $node->left, ' >> ', $node->right);
  253. }
  254. protected function pExpr_BinaryOp_Pow(BinaryOp\Pow $node) {
  255. return $this->pInfixOp(BinaryOp\Pow::class, $node->left, ' ** ', $node->right);
  256. }
  257. protected function pExpr_BinaryOp_LogicalAnd(BinaryOp\LogicalAnd $node) {
  258. return $this->pInfixOp(BinaryOp\LogicalAnd::class, $node->left, ' and ', $node->right);
  259. }
  260. protected function pExpr_BinaryOp_LogicalOr(BinaryOp\LogicalOr $node) {
  261. return $this->pInfixOp(BinaryOp\LogicalOr::class, $node->left, ' or ', $node->right);
  262. }
  263. protected function pExpr_BinaryOp_LogicalXor(BinaryOp\LogicalXor $node) {
  264. return $this->pInfixOp(BinaryOp\LogicalXor::class, $node->left, ' xor ', $node->right);
  265. }
  266. protected function pExpr_BinaryOp_Equal(BinaryOp\Equal $node) {
  267. return $this->pInfixOp(BinaryOp\Equal::class, $node->left, ' == ', $node->right);
  268. }
  269. protected function pExpr_BinaryOp_NotEqual(BinaryOp\NotEqual $node) {
  270. return $this->pInfixOp(BinaryOp\NotEqual::class, $node->left, ' != ', $node->right);
  271. }
  272. protected function pExpr_BinaryOp_Identical(BinaryOp\Identical $node) {
  273. return $this->pInfixOp(BinaryOp\Identical::class, $node->left, ' === ', $node->right);
  274. }
  275. protected function pExpr_BinaryOp_NotIdentical(BinaryOp\NotIdentical $node) {
  276. return $this->pInfixOp(BinaryOp\NotIdentical::class, $node->left, ' !== ', $node->right);
  277. }
  278. protected function pExpr_BinaryOp_Spaceship(BinaryOp\Spaceship $node) {
  279. return $this->pInfixOp(BinaryOp\Spaceship::class, $node->left, ' <=> ', $node->right);
  280. }
  281. protected function pExpr_BinaryOp_Greater(BinaryOp\Greater $node) {
  282. return $this->pInfixOp(BinaryOp\Greater::class, $node->left, ' > ', $node->right);
  283. }
  284. protected function pExpr_BinaryOp_GreaterOrEqual(BinaryOp\GreaterOrEqual $node) {
  285. return $this->pInfixOp(BinaryOp\GreaterOrEqual::class, $node->left, ' >= ', $node->right);
  286. }
  287. protected function pExpr_BinaryOp_Smaller(BinaryOp\Smaller $node) {
  288. return $this->pInfixOp(BinaryOp\Smaller::class, $node->left, ' < ', $node->right);
  289. }
  290. protected function pExpr_BinaryOp_SmallerOrEqual(BinaryOp\SmallerOrEqual $node) {
  291. return $this->pInfixOp(BinaryOp\SmallerOrEqual::class, $node->left, ' <= ', $node->right);
  292. }
  293. protected function pExpr_BinaryOp_Coalesce(BinaryOp\Coalesce $node) {
  294. return $this->pInfixOp(BinaryOp\Coalesce::class, $node->left, ' ?? ', $node->right);
  295. }
  296. protected function pExpr_Instanceof(Expr\Instanceof_ $node) {
  297. return $this->pInfixOp(Expr\Instanceof_::class, $node->expr, ' instanceof ', $node->class);
  298. }
  299. // Unary expressions
  300. protected function pExpr_BooleanNot(Expr\BooleanNot $node) {
  301. return $this->pPrefixOp(Expr\BooleanNot::class, '!', $node->expr);
  302. }
  303. protected function pExpr_BitwiseNot(Expr\BitwiseNot $node) {
  304. return $this->pPrefixOp(Expr\BitwiseNot::class, '~', $node->expr);
  305. }
  306. protected function pExpr_UnaryMinus(Expr\UnaryMinus $node) {
  307. if ($node->expr instanceof Expr\UnaryMinus || $node->expr instanceof Expr\PreDec) {
  308. // Enforce -(-$expr) instead of --$expr
  309. return '-(' . $this->p($node->expr) . ')';
  310. }
  311. return $this->pPrefixOp(Expr\UnaryMinus::class, '-', $node->expr);
  312. }
  313. protected function pExpr_UnaryPlus(Expr\UnaryPlus $node) {
  314. if ($node->expr instanceof Expr\UnaryPlus || $node->expr instanceof Expr\PreInc) {
  315. // Enforce +(+$expr) instead of ++$expr
  316. return '+(' . $this->p($node->expr) . ')';
  317. }
  318. return $this->pPrefixOp(Expr\UnaryPlus::class, '+', $node->expr);
  319. }
  320. protected function pExpr_PreInc(Expr\PreInc $node) {
  321. return $this->pPrefixOp(Expr\PreInc::class, '++', $node->var);
  322. }
  323. protected function pExpr_PreDec(Expr\PreDec $node) {
  324. return $this->pPrefixOp(Expr\PreDec::class, '--', $node->var);
  325. }
  326. protected function pExpr_PostInc(Expr\PostInc $node) {
  327. return $this->pPostfixOp(Expr\PostInc::class, $node->var, '++');
  328. }
  329. protected function pExpr_PostDec(Expr\PostDec $node) {
  330. return $this->pPostfixOp(Expr\PostDec::class, $node->var, '--');
  331. }
  332. protected function pExpr_ErrorSuppress(Expr\ErrorSuppress $node) {
  333. return $this->pPrefixOp(Expr\ErrorSuppress::class, '@', $node->expr);
  334. }
  335. protected function pExpr_YieldFrom(Expr\YieldFrom $node) {
  336. return $this->pPrefixOp(Expr\YieldFrom::class, 'yield from ', $node->expr);
  337. }
  338. protected function pExpr_Print(Expr\Print_ $node) {
  339. return $this->pPrefixOp(Expr\Print_::class, 'print ', $node->expr);
  340. }
  341. // Casts
  342. protected function pExpr_Cast_Int(Cast\Int_ $node) {
  343. return $this->pPrefixOp(Cast\Int_::class, '(int) ', $node->expr);
  344. }
  345. protected function pExpr_Cast_Double(Cast\Double $node) {
  346. $kind = $node->getAttribute('kind', Cast\Double::KIND_DOUBLE);
  347. if ($kind === Cast\Double::KIND_DOUBLE) {
  348. $cast = '(double)';
  349. } elseif ($kind === Cast\Double::KIND_FLOAT) {
  350. $cast = '(float)';
  351. } elseif ($kind === Cast\Double::KIND_REAL) {
  352. $cast = '(real)';
  353. }
  354. return $this->pPrefixOp(Cast\Double::class, $cast . ' ', $node->expr);
  355. }
  356. protected function pExpr_Cast_String(Cast\String_ $node) {
  357. return $this->pPrefixOp(Cast\String_::class, '(string) ', $node->expr);
  358. }
  359. protected function pExpr_Cast_Array(Cast\Array_ $node) {
  360. return $this->pPrefixOp(Cast\Array_::class, '(array) ', $node->expr);
  361. }
  362. protected function pExpr_Cast_Object(Cast\Object_ $node) {
  363. return $this->pPrefixOp(Cast\Object_::class, '(object) ', $node->expr);
  364. }
  365. protected function pExpr_Cast_Bool(Cast\Bool_ $node) {
  366. return $this->pPrefixOp(Cast\Bool_::class, '(bool) ', $node->expr);
  367. }
  368. protected function pExpr_Cast_Unset(Cast\Unset_ $node) {
  369. return $this->pPrefixOp(Cast\Unset_::class, '(unset) ', $node->expr);
  370. }
  371. // Function calls and similar constructs
  372. protected function pExpr_FuncCall(Expr\FuncCall $node) {
  373. return $this->pCallLhs($node->name)
  374. . '(' . $this->pMaybeMultiline($node->args) . ')';
  375. }
  376. protected function pExpr_MethodCall(Expr\MethodCall $node) {
  377. return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name)
  378. . '(' . $this->pMaybeMultiline($node->args) . ')';
  379. }
  380. protected function pExpr_StaticCall(Expr\StaticCall $node) {
  381. return $this->pDereferenceLhs($node->class) . '::'
  382. . ($node->name instanceof Expr
  383. ? ($node->name instanceof Expr\Variable
  384. ? $this->p($node->name)
  385. : '{' . $this->p($node->name) . '}')
  386. : $node->name)
  387. . '(' . $this->pMaybeMultiline($node->args) . ')';
  388. }
  389. protected function pExpr_Empty(Expr\Empty_ $node) {
  390. return 'empty(' . $this->p($node->expr) . ')';
  391. }
  392. protected function pExpr_Isset(Expr\Isset_ $node) {
  393. return 'isset(' . $this->pCommaSeparated($node->vars) . ')';
  394. }
  395. protected function pExpr_Eval(Expr\Eval_ $node) {
  396. return 'eval(' . $this->p($node->expr) . ')';
  397. }
  398. protected function pExpr_Include(Expr\Include_ $node) {
  399. static $map = [
  400. Expr\Include_::TYPE_INCLUDE => 'include',
  401. Expr\Include_::TYPE_INCLUDE_ONCE => 'include_once',
  402. Expr\Include_::TYPE_REQUIRE => 'require',
  403. Expr\Include_::TYPE_REQUIRE_ONCE => 'require_once',
  404. ];
  405. return $map[$node->type] . ' ' . $this->p($node->expr);
  406. }
  407. protected function pExpr_List(Expr\List_ $node) {
  408. return 'list(' . $this->pCommaSeparated($node->items) . ')';
  409. }
  410. // Other
  411. protected function pExpr_Error(Expr\Error $node) {
  412. throw new \LogicException('Cannot pretty-print AST with Error nodes');
  413. }
  414. protected function pExpr_Variable(Expr\Variable $node) {
  415. if ($node->name instanceof Expr) {
  416. return '${' . $this->p($node->name) . '}';
  417. } else {
  418. return '$' . $node->name;
  419. }
  420. }
  421. protected function pExpr_Array(Expr\Array_ $node) {
  422. $syntax = $node->getAttribute('kind',
  423. $this->options['shortArraySyntax'] ? Expr\Array_::KIND_SHORT : Expr\Array_::KIND_LONG);
  424. if ($syntax === Expr\Array_::KIND_SHORT) {
  425. return '[' . $this->pMaybeMultiline($node->items, true) . ']';
  426. } else {
  427. return 'array(' . $this->pMaybeMultiline($node->items, true) . ')';
  428. }
  429. }
  430. protected function pExpr_ArrayItem(Expr\ArrayItem $node) {
  431. return (null !== $node->key ? $this->p($node->key) . ' => ' : '')
  432. . ($node->byRef ? '&' : '') . $this->p($node->value);
  433. }
  434. protected function pExpr_ArrayDimFetch(Expr\ArrayDimFetch $node) {
  435. return $this->pDereferenceLhs($node->var)
  436. . '[' . (null !== $node->dim ? $this->p($node->dim) : '') . ']';
  437. }
  438. protected function pExpr_ConstFetch(Expr\ConstFetch $node) {
  439. return $this->p($node->name);
  440. }
  441. protected function pExpr_ClassConstFetch(Expr\ClassConstFetch $node) {
  442. return $this->p($node->class) . '::' . $this->p($node->name);
  443. }
  444. protected function pExpr_PropertyFetch(Expr\PropertyFetch $node) {
  445. return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name);
  446. }
  447. protected function pExpr_StaticPropertyFetch(Expr\StaticPropertyFetch $node) {
  448. return $this->pDereferenceLhs($node->class) . '::$' . $this->pObjectProperty($node->name);
  449. }
  450. protected function pExpr_ShellExec(Expr\ShellExec $node) {
  451. return '`' . $this->pEncapsList($node->parts, '`') . '`';
  452. }
  453. protected function pExpr_Closure(Expr\Closure $node) {
  454. return ($node->static ? 'static ' : '')
  455. . 'function ' . ($node->byRef ? '&' : '')
  456. . '(' . $this->pCommaSeparated($node->params) . ')'
  457. . (!empty($node->uses) ? ' use(' . $this->pCommaSeparated($node->uses) . ')' : '')
  458. . (null !== $node->returnType ? ' : ' . $this->p($node->returnType) : '')
  459. . ' {' . $this->pStmts($node->stmts) . $this->nl . '}';
  460. }
  461. protected function pExpr_ClosureUse(Expr\ClosureUse $node) {
  462. return ($node->byRef ? '&' : '') . $this->p($node->var);
  463. }
  464. protected function pExpr_New(Expr\New_ $node) {
  465. if ($node->class instanceof Stmt\Class_) {
  466. $args = $node->args ? '(' . $this->pMaybeMultiline($node->args) . ')' : '';
  467. return 'new ' . $this->pClassCommon($node->class, $args);
  468. }
  469. return 'new ' . $this->p($node->class) . '(' . $this->pMaybeMultiline($node->args) . ')';
  470. }
  471. protected function pExpr_Clone(Expr\Clone_ $node) {
  472. return 'clone ' . $this->p($node->expr);
  473. }
  474. protected function pExpr_Ternary(Expr\Ternary $node) {
  475. // a bit of cheating: we treat the ternary as a binary op where the ?...: part is the operator.
  476. // this is okay because the part between ? and : never needs parentheses.
  477. return $this->pInfixOp(Expr\Ternary::class,
  478. $node->cond, ' ?' . (null !== $node->if ? ' ' . $this->p($node->if) . ' ' : '') . ': ', $node->else
  479. );
  480. }
  481. protected function pExpr_Exit(Expr\Exit_ $node) {
  482. $kind = $node->getAttribute('kind', Expr\Exit_::KIND_DIE);
  483. return ($kind === Expr\Exit_::KIND_EXIT ? 'exit' : 'die')
  484. . (null !== $node->expr ? '(' . $this->p($node->expr) . ')' : '');
  485. }
  486. protected function pExpr_Yield(Expr\Yield_ $node) {
  487. if ($node->value === null) {
  488. return 'yield';
  489. } else {
  490. // this is a bit ugly, but currently there is no way to detect whether the parentheses are necessary
  491. return '(yield '
  492. . ($node->key !== null ? $this->p($node->key) . ' => ' : '')
  493. . $this->p($node->value)
  494. . ')';
  495. }
  496. }
  497. // Declarations
  498. protected function pStmt_Namespace(Stmt\Namespace_ $node) {
  499. if ($this->canUseSemicolonNamespaces) {
  500. return 'namespace ' . $this->p($node->name) . ';'
  501. . $this->nl . $this->pStmts($node->stmts, false);
  502. } else {
  503. return 'namespace' . (null !== $node->name ? ' ' . $this->p($node->name) : '')
  504. . ' {' . $this->pStmts($node->stmts) . $this->nl . '}';
  505. }
  506. }
  507. protected function pStmt_Use(Stmt\Use_ $node) {
  508. return 'use ' . $this->pUseType($node->type)
  509. . $this->pCommaSeparated($node->uses) . ';';
  510. }
  511. protected function pStmt_GroupUse(Stmt\GroupUse $node) {
  512. return 'use ' . $this->pUseType($node->type) . $this->pName($node->prefix)
  513. . '\{' . $this->pCommaSeparated($node->uses) . '};';
  514. }
  515. protected function pStmt_UseUse(Stmt\UseUse $node) {
  516. return $this->pUseType($node->type) . $this->p($node->name)
  517. . (null !== $node->alias ? ' as ' . $node->alias : '');
  518. }
  519. protected function pUseType($type) {
  520. return $type === Stmt\Use_::TYPE_FUNCTION ? 'function '
  521. : ($type === Stmt\Use_::TYPE_CONSTANT ? 'const ' : '');
  522. }
  523. protected function pStmt_Interface(Stmt\Interface_ $node) {
  524. return 'interface ' . $node->name
  525. . (!empty($node->extends) ? ' extends ' . $this->pCommaSeparated($node->extends) : '')
  526. . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
  527. }
  528. protected function pStmt_Class(Stmt\Class_ $node) {
  529. return $this->pClassCommon($node, ' ' . $node->name);
  530. }
  531. protected function pStmt_Trait(Stmt\Trait_ $node) {
  532. return 'trait ' . $node->name
  533. . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
  534. }
  535. protected function pStmt_TraitUse(Stmt\TraitUse $node) {
  536. return 'use ' . $this->pCommaSeparated($node->traits)
  537. . (empty($node->adaptations)
  538. ? ';'
  539. : ' {' . $this->pStmts($node->adaptations) . $this->nl . '}');
  540. }
  541. protected function pStmt_TraitUseAdaptation_Precedence(Stmt\TraitUseAdaptation\Precedence $node) {
  542. return $this->p($node->trait) . '::' . $node->method
  543. . ' insteadof ' . $this->pCommaSeparated($node->insteadof) . ';';
  544. }
  545. protected function pStmt_TraitUseAdaptation_Alias(Stmt\TraitUseAdaptation\Alias $node) {
  546. return (null !== $node->trait ? $this->p($node->trait) . '::' : '')
  547. . $node->method . ' as'
  548. . (null !== $node->newModifier ? ' ' . rtrim($this->pModifiers($node->newModifier), ' ') : '')
  549. . (null !== $node->newName ? ' ' . $node->newName : '')
  550. . ';';
  551. }
  552. protected function pStmt_Property(Stmt\Property $node) {
  553. return (0 === $node->flags ? 'var ' : $this->pModifiers($node->flags))
  554. . ($node->type ? $this->p($node->type) . ' ' : '')
  555. . $this->pCommaSeparated($node->props) . ';';
  556. }
  557. protected function pStmt_PropertyProperty(Stmt\PropertyProperty $node) {
  558. return '$' . $node->name
  559. . (null !== $node->default ? ' = ' . $this->p($node->default) : '');
  560. }
  561. protected function pStmt_ClassMethod(Stmt\ClassMethod $node) {
  562. return $this->pModifiers($node->flags)
  563. . 'function ' . ($node->byRef ? '&' : '') . $node->name
  564. . '(' . $this->pCommaSeparated($node->params) . ')'
  565. . (null !== $node->returnType ? ' : ' . $this->p($node->returnType) : '')
  566. . (null !== $node->stmts
  567. ? $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'
  568. : ';');
  569. }
  570. protected function pStmt_ClassConst(Stmt\ClassConst $node) {
  571. return $this->pModifiers($node->flags)
  572. . 'const ' . $this->pCommaSeparated($node->consts) . ';';
  573. }
  574. protected function pStmt_Function(Stmt\Function_ $node) {
  575. return 'function ' . ($node->byRef ? '&' : '') . $node->name
  576. . '(' . $this->pCommaSeparated($node->params) . ')'
  577. . (null !== $node->returnType ? ' : ' . $this->p($node->returnType) : '')
  578. . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
  579. }
  580. protected function pStmt_Const(Stmt\Const_ $node) {
  581. return 'const ' . $this->pCommaSeparated($node->consts) . ';';
  582. }
  583. protected function pStmt_Declare(Stmt\Declare_ $node) {
  584. return 'declare (' . $this->pCommaSeparated($node->declares) . ')'
  585. . (null !== $node->stmts ? ' {' . $this->pStmts($node->stmts) . $this->nl . '}' : ';');
  586. }
  587. protected function pStmt_DeclareDeclare(Stmt\DeclareDeclare $node) {
  588. return $node->key . '=' . $this->p($node->value);
  589. }
  590. // Control flow
  591. protected function pStmt_If(Stmt\If_ $node) {
  592. return 'if (' . $this->p($node->cond) . ') {'
  593. . $this->pStmts($node->stmts) . $this->nl . '}'
  594. . ($node->elseifs ? ' ' . $this->pImplode($node->elseifs, ' ') : '')
  595. . (null !== $node->else ? ' ' . $this->p($node->else) : '');
  596. }
  597. protected function pStmt_ElseIf(Stmt\ElseIf_ $node) {
  598. return 'elseif (' . $this->p($node->cond) . ') {'
  599. . $this->pStmts($node->stmts) . $this->nl . '}';
  600. }
  601. protected function pStmt_Else(Stmt\Else_ $node) {
  602. return 'else {' . $this->pStmts($node->stmts) . $this->nl . '}';
  603. }
  604. protected function pStmt_For(Stmt\For_ $node) {
  605. return 'for ('
  606. . $this->pCommaSeparated($node->init) . ';' . (!empty($node->cond) ? ' ' : '')
  607. . $this->pCommaSeparated($node->cond) . ';' . (!empty($node->loop) ? ' ' : '')
  608. . $this->pCommaSeparated($node->loop)
  609. . ') {' . $this->pStmts($node->stmts) . $this->nl . '}';
  610. }
  611. protected function pStmt_Foreach(Stmt\Foreach_ $node) {
  612. return 'foreach (' . $this->p($node->expr) . ' as '
  613. . (null !== $node->keyVar ? $this->p($node->keyVar) . ' => ' : '')
  614. . ($node->byRef ? '&' : '') . $this->p($node->valueVar) . ') {'
  615. . $this->pStmts($node->stmts) . $this->nl . '}';
  616. }
  617. protected function pStmt_While(Stmt\While_ $node) {
  618. return 'while (' . $this->p($node->cond) . ') {'
  619. . $this->pStmts($node->stmts) . $this->nl . '}';
  620. }
  621. protected function pStmt_Do(Stmt\Do_ $node) {
  622. return 'do {' . $this->pStmts($node->stmts) . $this->nl
  623. . '} while (' . $this->p($node->cond) . ');';
  624. }
  625. protected function pStmt_Switch(Stmt\Switch_ $node) {
  626. return 'switch (' . $this->p($node->cond) . ') {'
  627. . $this->pStmts($node->cases) . $this->nl . '}';
  628. }
  629. protected function pStmt_Case(Stmt\Case_ $node) {
  630. return (null !== $node->cond ? 'case ' . $this->p($node->cond) : 'default') . ':'
  631. . $this->pStmts($node->stmts);
  632. }
  633. protected function pStmt_TryCatch(Stmt\TryCatch $node) {
  634. return 'try {' . $this->pStmts($node->stmts) . $this->nl . '}'
  635. . ($node->catches ? ' ' . $this->pImplode($node->catches, ' ') : '')
  636. . ($node->finally !== null ? ' ' . $this->p($node->finally) : '');
  637. }
  638. protected function pStmt_Catch(Stmt\Catch_ $node) {
  639. return 'catch (' . $this->pImplode($node->types, '|') . ' '
  640. . $this->p($node->var)
  641. . ') {' . $this->pStmts($node->stmts) . $this->nl . '}';
  642. }
  643. protected function pStmt_Finally(Stmt\Finally_ $node) {
  644. return 'finally {' . $this->pStmts($node->stmts) . $this->nl . '}';
  645. }
  646. protected function pStmt_Break(Stmt\Break_ $node) {
  647. return 'break' . ($node->num !== null ? ' ' . $this->p($node->num) : '') . ';';
  648. }
  649. protected function pStmt_Continue(Stmt\Continue_ $node) {
  650. return 'continue' . ($node->num !== null ? ' ' . $this->p($node->num) : '') . ';';
  651. }
  652. protected function pStmt_Return(Stmt\Return_ $node) {
  653. return 'return' . (null !== $node->expr ? ' ' . $this->p($node->expr) : '') . ';';
  654. }
  655. protected function pStmt_Throw(Stmt\Throw_ $node) {
  656. return 'throw ' . $this->p($node->expr) . ';';
  657. }
  658. protected function pStmt_Label(Stmt\Label $node) {
  659. return $node->name . ':';
  660. }
  661. protected function pStmt_Goto(Stmt\Goto_ $node) {
  662. return 'goto ' . $node->name . ';';
  663. }
  664. // Other
  665. protected function pStmt_Expression(Stmt\Expression $node) {
  666. return $this->p($node->expr) . ';';
  667. }
  668. protected function pStmt_Echo(Stmt\Echo_ $node) {
  669. return 'echo ' . $this->pCommaSeparated($node->exprs) . ';';
  670. }
  671. protected function pStmt_Static(Stmt\Static_ $node) {
  672. return 'static ' . $this->pCommaSeparated($node->vars) . ';';
  673. }
  674. protected function pStmt_Global(Stmt\Global_ $node) {
  675. return 'global ' . $this->pCommaSeparated($node->vars) . ';';
  676. }
  677. protected function pStmt_StaticVar(Stmt\StaticVar $node) {
  678. return $this->p($node->var)
  679. . (null !== $node->default ? ' = ' . $this->p($node->default) : '');
  680. }
  681. protected function pStmt_Unset(Stmt\Unset_ $node) {
  682. return 'unset(' . $this->pCommaSeparated($node->vars) . ');';
  683. }
  684. protected function pStmt_InlineHTML(Stmt\InlineHTML $node) {
  685. $newline = $node->getAttribute('hasLeadingNewline', true) ? "\n" : '';
  686. return '?>' . $newline . $node->value . '<?php ';
  687. }
  688. protected function pStmt_HaltCompiler(Stmt\HaltCompiler $node) {
  689. return '__halt_compiler();' . $node->remaining;
  690. }
  691. protected function pStmt_Nop(Stmt\Nop $node) {
  692. return '';
  693. }
  694. // Helpers
  695. protected function pClassCommon(Stmt\Class_ $node, $afterClassToken) {
  696. return $this->pModifiers($node->flags)
  697. . 'class' . $afterClassToken
  698. . (null !== $node->extends ? ' extends ' . $this->p($node->extends) : '')
  699. . (!empty($node->implements) ? ' implements ' . $this->pCommaSeparated($node->implements) : '')
  700. . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
  701. }
  702. protected function pObjectProperty($node) {
  703. if ($node instanceof Expr) {
  704. return '{' . $this->p($node) . '}';
  705. } else {
  706. return $node;
  707. }
  708. }
  709. protected function pEncapsList(array $encapsList, $quote) {
  710. $return = '';
  711. foreach ($encapsList as $element) {
  712. if ($element instanceof Scalar\EncapsedStringPart) {
  713. $return .= $this->escapeString($element->value, $quote);
  714. } else {
  715. $return .= '{' . $this->p($element) . '}';
  716. }
  717. }
  718. return $return;
  719. }
  720. protected function pSingleQuotedString(string $string) {
  721. return '\'' . addcslashes($string, '\'\\') . '\'';
  722. }
  723. protected function escapeString($string, $quote) {
  724. if (null === $quote) {
  725. // For doc strings, don't escape newlines
  726. $escaped = addcslashes($string, "\t\f\v$\\");
  727. } else {
  728. $escaped = addcslashes($string, "\n\r\t\f\v$" . $quote . "\\");
  729. }
  730. // Escape other control characters
  731. return preg_replace_callback('/([\0-\10\16-\37])(?=([0-7]?))/', function ($matches) {
  732. $oct = decoct(ord($matches[1]));
  733. if ($matches[2] !== '') {
  734. // If there is a trailing digit, use the full three character form
  735. return '\\' . str_pad($oct, 3, '0', \STR_PAD_LEFT);
  736. }
  737. return '\\' . $oct;
  738. }, $escaped);
  739. }
  740. protected function containsEndLabel($string, $label, $atStart = true, $atEnd = true) {
  741. $start = $atStart ? '(?:^|[\r\n])' : '[\r\n]';
  742. $end = $atEnd ? '(?:$|[;\r\n])' : '[;\r\n]';
  743. return false !== strpos($string, $label)
  744. && preg_match('/' . $start . $label . $end . '/', $string);
  745. }
  746. protected function encapsedContainsEndLabel(array $parts, $label) {
  747. foreach ($parts as $i => $part) {
  748. $atStart = $i === 0;
  749. $atEnd = $i === count($parts) - 1;
  750. if ($part instanceof Scalar\EncapsedStringPart
  751. && $this->containsEndLabel($part->value, $label, $atStart, $atEnd)
  752. ) {
  753. return true;
  754. }
  755. }
  756. return false;
  757. }
  758. protected function pDereferenceLhs(Node $node) {
  759. if (!$this->dereferenceLhsRequiresParens($node)) {
  760. return $this->p($node);
  761. } else {
  762. return '(' . $this->p($node) . ')';
  763. }
  764. }
  765. protected function pCallLhs(Node $node) {
  766. if (!$this->callLhsRequiresParens($node)) {
  767. return $this->p($node);
  768. } else {
  769. return '(' . $this->p($node) . ')';
  770. }
  771. }
  772. /**
  773. * @param Node[] $nodes
  774. * @return bool
  775. */
  776. private function hasNodeWithComments(array $nodes) {
  777. foreach ($nodes as $node) {
  778. if ($node && $node->getComments()) {
  779. return true;
  780. }
  781. }
  782. return false;
  783. }
  784. private function pMaybeMultiline(array $nodes, $trailingComma = false) {
  785. if (!$this->hasNodeWithComments($nodes)) {
  786. return $this->pCommaSeparated($nodes);
  787. } else {
  788. return $this->pCommaSeparatedMultiline($nodes, $trailingComma) . $this->nl;
  789. }
  790. }
  791. }