Standard.php 51 KB

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