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