Standard.php 42 KB

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