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