Standard.php 40 KB

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