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