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