Debian Codegraph @

vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter/Standard.php

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