Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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     protected function pScalar_EncapsedStringPart(Scalar\EncapsedStringPart $node) {
202         throw new \LogicException('Cannot directly print EncapsedStringPart');
203     }
204
205     // Assignments
206
207     protected function pExpr_Assign(Expr\Assign $node) {
208         return $this->pInfixOp(Expr\Assign::class, $node->var, ' = ', $node->expr);
209     }
210
211     protected function pExpr_AssignRef(Expr\AssignRef $node) {
212         return $this->pInfixOp(Expr\AssignRef::class, $node->var, ' =& ', $node->expr);
213     }
214
215     protected function pExpr_AssignOp_Plus(AssignOp\Plus $node) {
216         return $this->pInfixOp(AssignOp\Plus::class, $node->var, ' += ', $node->expr);
217     }
218
219     protected function pExpr_AssignOp_Minus(AssignOp\Minus $node) {
220         return $this->pInfixOp(AssignOp\Minus::class, $node->var, ' -= ', $node->expr);
221     }
222
223     protected function pExpr_AssignOp_Mul(AssignOp\Mul $node) {
224         return $this->pInfixOp(AssignOp\Mul::class, $node->var, ' *= ', $node->expr);
225     }
226
227     protected function pExpr_AssignOp_Div(AssignOp\Div $node) {
228         return $this->pInfixOp(AssignOp\Div::class, $node->var, ' /= ', $node->expr);
229     }
230
231     protected function pExpr_AssignOp_Concat(AssignOp\Concat $node) {
232         return $this->pInfixOp(AssignOp\Concat::class, $node->var, ' .= ', $node->expr);
233     }
234
235     protected function pExpr_AssignOp_Mod(AssignOp\Mod $node) {
236         return $this->pInfixOp(AssignOp\Mod::class, $node->var, ' %= ', $node->expr);
237     }
238
239     protected function pExpr_AssignOp_BitwiseAnd(AssignOp\BitwiseAnd $node) {
240         return $this->pInfixOp(AssignOp\BitwiseAnd::class, $node->var, ' &= ', $node->expr);
241     }
242
243     protected function pExpr_AssignOp_BitwiseOr(AssignOp\BitwiseOr $node) {
244         return $this->pInfixOp(AssignOp\BitwiseOr::class, $node->var, ' |= ', $node->expr);
245     }
246
247     protected function pExpr_AssignOp_BitwiseXor(AssignOp\BitwiseXor $node) {
248         return $this->pInfixOp(AssignOp\BitwiseXor::class, $node->var, ' ^= ', $node->expr);
249     }
250
251     protected function pExpr_AssignOp_ShiftLeft(AssignOp\ShiftLeft $node) {
252         return $this->pInfixOp(AssignOp\ShiftLeft::class, $node->var, ' <<= ', $node->expr);
253     }
254
255     protected function pExpr_AssignOp_ShiftRight(AssignOp\ShiftRight $node) {
256         return $this->pInfixOp(AssignOp\ShiftRight::class, $node->var, ' >>= ', $node->expr);
257     }
258
259     protected function pExpr_AssignOp_Pow(AssignOp\Pow $node) {
260         return $this->pInfixOp(AssignOp\Pow::class, $node->var, ' **= ', $node->expr);
261     }
262
263     // Binary expressions
264
265     protected function pExpr_BinaryOp_Plus(BinaryOp\Plus $node) {
266         return $this->pInfixOp(BinaryOp\Plus::class, $node->left, ' + ', $node->right);
267     }
268
269     protected function pExpr_BinaryOp_Minus(BinaryOp\Minus $node) {
270         return $this->pInfixOp(BinaryOp\Minus::class, $node->left, ' - ', $node->right);
271     }
272
273     protected function pExpr_BinaryOp_Mul(BinaryOp\Mul $node) {
274         return $this->pInfixOp(BinaryOp\Mul::class, $node->left, ' * ', $node->right);
275     }
276
277     protected function pExpr_BinaryOp_Div(BinaryOp\Div $node) {
278         return $this->pInfixOp(BinaryOp\Div::class, $node->left, ' / ', $node->right);
279     }
280
281     protected function pExpr_BinaryOp_Concat(BinaryOp\Concat $node) {
282         return $this->pInfixOp(BinaryOp\Concat::class, $node->left, ' . ', $node->right);
283     }
284
285     protected function pExpr_BinaryOp_Mod(BinaryOp\Mod $node) {
286         return $this->pInfixOp(BinaryOp\Mod::class, $node->left, ' % ', $node->right);
287     }
288
289     protected function pExpr_BinaryOp_BooleanAnd(BinaryOp\BooleanAnd $node) {
290         return $this->pInfixOp(BinaryOp\BooleanAnd::class, $node->left, ' && ', $node->right);
291     }
292
293     protected function pExpr_BinaryOp_BooleanOr(BinaryOp\BooleanOr $node) {
294         return $this->pInfixOp(BinaryOp\BooleanOr::class, $node->left, ' || ', $node->right);
295     }
296
297     protected function pExpr_BinaryOp_BitwiseAnd(BinaryOp\BitwiseAnd $node) {
298         return $this->pInfixOp(BinaryOp\BitwiseAnd::class, $node->left, ' & ', $node->right);
299     }
300
301     protected function pExpr_BinaryOp_BitwiseOr(BinaryOp\BitwiseOr $node) {
302         return $this->pInfixOp(BinaryOp\BitwiseOr::class, $node->left, ' | ', $node->right);
303     }
304
305     protected function pExpr_BinaryOp_BitwiseXor(BinaryOp\BitwiseXor $node) {
306         return $this->pInfixOp(BinaryOp\BitwiseXor::class, $node->left, ' ^ ', $node->right);
307     }
308
309     protected function pExpr_BinaryOp_ShiftLeft(BinaryOp\ShiftLeft $node) {
310         return $this->pInfixOp(BinaryOp\ShiftLeft::class, $node->left, ' << ', $node->right);
311     }
312
313     protected function pExpr_BinaryOp_ShiftRight(BinaryOp\ShiftRight $node) {
314         return $this->pInfixOp(BinaryOp\ShiftRight::class, $node->left, ' >> ', $node->right);
315     }
316
317     protected function pExpr_BinaryOp_Pow(BinaryOp\Pow $node) {
318         return $this->pInfixOp(BinaryOp\Pow::class, $node->left, ' ** ', $node->right);
319     }
320
321     protected function pExpr_BinaryOp_LogicalAnd(BinaryOp\LogicalAnd $node) {
322         return $this->pInfixOp(BinaryOp\LogicalAnd::class, $node->left, ' and ', $node->right);
323     }
324
325     protected function pExpr_BinaryOp_LogicalOr(BinaryOp\LogicalOr $node) {
326         return $this->pInfixOp(BinaryOp\LogicalOr::class, $node->left, ' or ', $node->right);
327     }
328
329     protected function pExpr_BinaryOp_LogicalXor(BinaryOp\LogicalXor $node) {
330         return $this->pInfixOp(BinaryOp\LogicalXor::class, $node->left, ' xor ', $node->right);
331     }
332
333     protected function pExpr_BinaryOp_Equal(BinaryOp\Equal $node) {
334         return $this->pInfixOp(BinaryOp\Equal::class, $node->left, ' == ', $node->right);
335     }
336
337     protected function pExpr_BinaryOp_NotEqual(BinaryOp\NotEqual $node) {
338         return $this->pInfixOp(BinaryOp\NotEqual::class, $node->left, ' != ', $node->right);
339     }
340
341     protected function pExpr_BinaryOp_Identical(BinaryOp\Identical $node) {
342         return $this->pInfixOp(BinaryOp\Identical::class, $node->left, ' === ', $node->right);
343     }
344
345     protected function pExpr_BinaryOp_NotIdentical(BinaryOp\NotIdentical $node) {
346         return $this->pInfixOp(BinaryOp\NotIdentical::class, $node->left, ' !== ', $node->right);
347     }
348
349     protected function pExpr_BinaryOp_Spaceship(BinaryOp\Spaceship $node) {
350         return $this->pInfixOp(BinaryOp\Spaceship::class, $node->left, ' <=> ', $node->right);
351     }
352
353     protected function pExpr_BinaryOp_Greater(BinaryOp\Greater $node) {
354         return $this->pInfixOp(BinaryOp\Greater::class, $node->left, ' > ', $node->right);
355     }
356
357     protected function pExpr_BinaryOp_GreaterOrEqual(BinaryOp\GreaterOrEqual $node) {
358         return $this->pInfixOp(BinaryOp\GreaterOrEqual::class, $node->left, ' >= ', $node->right);
359     }
360
361     protected function pExpr_BinaryOp_Smaller(BinaryOp\Smaller $node) {
362         return $this->pInfixOp(BinaryOp\Smaller::class, $node->left, ' < ', $node->right);
363     }
364
365     protected function pExpr_BinaryOp_SmallerOrEqual(BinaryOp\SmallerOrEqual $node) {
366         return $this->pInfixOp(BinaryOp\SmallerOrEqual::class, $node->left, ' <= ', $node->right);
367     }
368
369     protected function pExpr_BinaryOp_Coalesce(BinaryOp\Coalesce $node) {
370         return $this->pInfixOp(BinaryOp\Coalesce::class, $node->left, ' ?? ', $node->right);
371     }
372
373     protected function pExpr_Instanceof(Expr\Instanceof_ $node) {
374         return $this->pInfixOp(Expr\Instanceof_::class, $node->expr, ' instanceof ', $node->class);
375     }
376
377     // Unary expressions
378
379     protected function pExpr_BooleanNot(Expr\BooleanNot $node) {
380         return $this->pPrefixOp(Expr\BooleanNot::class, '!', $node->expr);
381     }
382
383     protected function pExpr_BitwiseNot(Expr\BitwiseNot $node) {
384         return $this->pPrefixOp(Expr\BitwiseNot::class, '~', $node->expr);
385     }
386
387     protected function pExpr_UnaryMinus(Expr\UnaryMinus $node) {
388         if ($node->expr instanceof Expr\UnaryMinus || $node->expr instanceof Expr\PreDec) {
389             // Enforce -(-$expr) instead of --$expr
390             return '-(' . $this->p($node->expr) . ')';
391         }
392         return $this->pPrefixOp(Expr\UnaryMinus::class, '-', $node->expr);
393     }
394
395     protected function pExpr_UnaryPlus(Expr\UnaryPlus $node) {
396         if ($node->expr instanceof Expr\UnaryPlus || $node->expr instanceof Expr\PreInc) {
397             // Enforce +(+$expr) instead of ++$expr
398             return '+(' . $this->p($node->expr) . ')';
399         }
400         return $this->pPrefixOp(Expr\UnaryPlus::class, '+', $node->expr);
401     }
402
403     protected function pExpr_PreInc(Expr\PreInc $node) {
404         return $this->pPrefixOp(Expr\PreInc::class, '++', $node->var);
405     }
406
407     protected function pExpr_PreDec(Expr\PreDec $node) {
408         return $this->pPrefixOp(Expr\PreDec::class, '--', $node->var);
409     }
410
411     protected function pExpr_PostInc(Expr\PostInc $node) {
412         return $this->pPostfixOp(Expr\PostInc::class, $node->var, '++');
413     }
414
415     protected function pExpr_PostDec(Expr\PostDec $node) {
416         return $this->pPostfixOp(Expr\PostDec::class, $node->var, '--');
417     }
418
419     protected function pExpr_ErrorSuppress(Expr\ErrorSuppress $node) {
420         return $this->pPrefixOp(Expr\ErrorSuppress::class, '@', $node->expr);
421     }
422
423     protected function pExpr_YieldFrom(Expr\YieldFrom $node) {
424         return $this->pPrefixOp(Expr\YieldFrom::class, 'yield from ', $node->expr);
425     }
426
427     protected function pExpr_Print(Expr\Print_ $node) {
428         return $this->pPrefixOp(Expr\Print_::class, 'print ', $node->expr);
429     }
430
431     // Casts
432
433     protected function pExpr_Cast_Int(Cast\Int_ $node) {
434         return $this->pPrefixOp(Cast\Int_::class, '(int) ', $node->expr);
435     }
436
437     protected function pExpr_Cast_Double(Cast\Double $node) {
438         return $this->pPrefixOp(Cast\Double::class, '(double) ', $node->expr);
439     }
440
441     protected function pExpr_Cast_String(Cast\String_ $node) {
442         return $this->pPrefixOp(Cast\String_::class, '(string) ', $node->expr);
443     }
444
445     protected function pExpr_Cast_Array(Cast\Array_ $node) {
446         return $this->pPrefixOp(Cast\Array_::class, '(array) ', $node->expr);
447     }
448
449     protected function pExpr_Cast_Object(Cast\Object_ $node) {
450         return $this->pPrefixOp(Cast\Object_::class, '(object) ', $node->expr);
451     }
452
453     protected function pExpr_Cast_Bool(Cast\Bool_ $node) {
454         return $this->pPrefixOp(Cast\Bool_::class, '(bool) ', $node->expr);
455     }
456
457     protected function pExpr_Cast_Unset(Cast\Unset_ $node) {
458         return $this->pPrefixOp(Cast\Unset_::class, '(unset) ', $node->expr);
459     }
460
461     // Function calls and similar constructs
462
463     protected function pExpr_FuncCall(Expr\FuncCall $node) {
464         return $this->pCallLhs($node->name)
465              . '(' . $this->pMaybeMultiline($node->args) . ')';
466     }
467
468     protected function pExpr_MethodCall(Expr\MethodCall $node) {
469         return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name)
470              . '(' . $this->pMaybeMultiline($node->args) . ')';
471     }
472
473     protected function pExpr_StaticCall(Expr\StaticCall $node) {
474         return $this->pDereferenceLhs($node->class) . '::'
475              . ($node->name instanceof Expr
476                 ? ($node->name instanceof Expr\Variable
477                    ? $this->p($node->name)
478                    : '{' . $this->p($node->name) . '}')
479                 : $node->name)
480              . '(' . $this->pMaybeMultiline($node->args) . ')';
481     }
482
483     protected function pExpr_Empty(Expr\Empty_ $node) {
484         return 'empty(' . $this->p($node->expr) . ')';
485     }
486
487     protected function pExpr_Isset(Expr\Isset_ $node) {
488         return 'isset(' . $this->pCommaSeparated($node->vars) . ')';
489     }
490
491     protected function pExpr_Eval(Expr\Eval_ $node) {
492         return 'eval(' . $this->p($node->expr) . ')';
493     }
494
495     protected function pExpr_Include(Expr\Include_ $node) {
496         static $map = [
497             Expr\Include_::TYPE_INCLUDE      => 'include',
498             Expr\Include_::TYPE_INCLUDE_ONCE => 'include_once',
499             Expr\Include_::TYPE_REQUIRE      => 'require',
500             Expr\Include_::TYPE_REQUIRE_ONCE => 'require_once',
501         ];
502
503         return $map[$node->type] . ' ' . $this->p($node->expr);
504     }
505
506     protected function pExpr_List(Expr\List_ $node) {
507         return 'list(' . $this->pCommaSeparated($node->items) . ')';
508     }
509
510     // Other
511
512     protected function pExpr_Error(Expr\Error $node) {
513         throw new \LogicException('Cannot pretty-print AST with Error nodes');
514     }
515
516     protected function pExpr_Variable(Expr\Variable $node) {
517         if ($node->name instanceof Expr) {
518             return '${' . $this->p($node->name) . '}';
519         } else {
520             return '$' . $node->name;
521         }
522     }
523
524     protected function pExpr_Array(Expr\Array_ $node) {
525         $syntax = $node->getAttribute('kind',
526             $this->options['shortArraySyntax'] ? Expr\Array_::KIND_SHORT : Expr\Array_::KIND_LONG);
527         if ($syntax === Expr\Array_::KIND_SHORT) {
528             return '[' . $this->pMaybeMultiline($node->items, true) . ']';
529         } else {
530             return 'array(' . $this->pMaybeMultiline($node->items, true) . ')';
531         }
532     }
533
534     protected function pExpr_ArrayItem(Expr\ArrayItem $node) {
535         return (null !== $node->key ? $this->p($node->key) . ' => ' : '')
536              . ($node->byRef ? '&' : '') . $this->p($node->value);
537     }
538
539     protected function pExpr_ArrayDimFetch(Expr\ArrayDimFetch $node) {
540         return $this->pDereferenceLhs($node->var)
541              . '[' . (null !== $node->dim ? $this->p($node->dim) : '') . ']';
542     }
543
544     protected function pExpr_ConstFetch(Expr\ConstFetch $node) {
545         return $this->p($node->name);
546     }
547
548     protected function pExpr_ClassConstFetch(Expr\ClassConstFetch $node) {
549         return $this->p($node->class) . '::' . $this->p($node->name);
550     }
551
552     protected function pExpr_PropertyFetch(Expr\PropertyFetch $node) {
553         return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name);
554     }
555
556     protected function pExpr_StaticPropertyFetch(Expr\StaticPropertyFetch $node) {
557         return $this->pDereferenceLhs($node->class) . '::$' . $this->pObjectProperty($node->name);
558     }
559
560     protected function pExpr_ShellExec(Expr\ShellExec $node) {
561         return '`' . $this->pEncapsList($node->parts, '`') . '`';
562     }
563
564     protected function pExpr_Closure(Expr\Closure $node) {
565         return ($node->static ? 'static ' : '')
566              . 'function ' . ($node->byRef ? '&' : '')
567              . '(' . $this->pCommaSeparated($node->params) . ')'
568              . (!empty($node->uses) ? ' use(' . $this->pCommaSeparated($node->uses) . ')' : '')
569              . (null !== $node->returnType ? ' : ' . $this->p($node->returnType) : '')
570              . ' {' . $this->pStmts($node->stmts) . $this->nl . '}';
571     }
572
573     protected function pExpr_ClosureUse(Expr\ClosureUse $node) {
574         return ($node->byRef ? '&' : '') . $this->p($node->var);
575     }
576
577     protected function pExpr_New(Expr\New_ $node) {
578         if ($node->class instanceof Stmt\Class_) {
579             $args = $node->args ? '(' . $this->pMaybeMultiline($node->args) . ')' : '';
580             return 'new ' . $this->pClassCommon($node->class, $args);
581         }
582         return 'new ' . $this->p($node->class) . '(' . $this->pMaybeMultiline($node->args) . ')';
583     }
584
585     protected function pExpr_Clone(Expr\Clone_ $node) {
586         return 'clone ' . $this->p($node->expr);
587     }
588
589     protected function pExpr_Ternary(Expr\Ternary $node) {
590         // a bit of cheating: we treat the ternary as a binary op where the ?...: part is the operator.
591         // this is okay because the part between ? and : never needs parentheses.
592         return $this->pInfixOp(Expr\Ternary::class,
593             $node->cond, ' ?' . (null !== $node->if ? ' ' . $this->p($node->if) . ' ' : '') . ': ', $node->else
594         );
595     }
596
597     protected function pExpr_Exit(Expr\Exit_ $node) {
598         $kind = $node->getAttribute('kind', Expr\Exit_::KIND_DIE);
599         return ($kind === Expr\Exit_::KIND_EXIT ? 'exit' : 'die')
600              . (null !== $node->expr ? '(' . $this->p($node->expr) . ')' : '');
601     }
602
603     protected function pExpr_Yield(Expr\Yield_ $node) {
604         if ($node->value === null) {
605             return 'yield';
606         } else {
607             // this is a bit ugly, but currently there is no way to detect whether the parentheses are necessary
608             return '(yield '
609                  . ($node->key !== null ? $this->p($node->key) . ' => ' : '')
610                  . $this->p($node->value)
611                  . ')';
612         }
613     }
614
615     // Declarations
616
617     protected function pStmt_Namespace(Stmt\Namespace_ $node) {
618         if ($this->canUseSemicolonNamespaces) {
619             return 'namespace ' . $this->p($node->name) . ';'
620                  . $this->nl . $this->pStmts($node->stmts, false);
621         } else {
622             return 'namespace' . (null !== $node->name ? ' ' . $this->p($node->name) : '')
623                  . ' {' . $this->pStmts($node->stmts) . $this->nl . '}';
624         }
625     }
626
627     protected function pStmt_Use(Stmt\Use_ $node) {
628         return 'use ' . $this->pUseType($node->type)
629              . $this->pCommaSeparated($node->uses) . ';';
630     }
631
632     protected function pStmt_GroupUse(Stmt\GroupUse $node) {
633         return 'use ' . $this->pUseType($node->type) . $this->pName($node->prefix)
634              . '\{' . $this->pCommaSeparated($node->uses) . '};';
635     }
636
637     protected function pStmt_UseUse(Stmt\UseUse $node) {
638         return $this->pUseType($node->type) . $this->p($node->name)
639              . (null !== $node->alias ? ' as ' . $node->alias : '');
640     }
641
642     protected function pUseType($type) {
643         return $type === Stmt\Use_::TYPE_FUNCTION ? 'function '
644             : ($type === Stmt\Use_::TYPE_CONSTANT ? 'const ' : '');
645     }
646
647     protected function pStmt_Interface(Stmt\Interface_ $node) {
648         return 'interface ' . $node->name
649              . (!empty($node->extends) ? ' extends ' . $this->pCommaSeparated($node->extends) : '')
650              . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
651     }
652
653     protected function pStmt_Class(Stmt\Class_ $node) {
654         return $this->pClassCommon($node, ' ' . $node->name);
655     }
656
657     protected function pStmt_Trait(Stmt\Trait_ $node) {
658         return 'trait ' . $node->name
659              . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
660     }
661
662     protected function pStmt_TraitUse(Stmt\TraitUse $node) {
663         return 'use ' . $this->pCommaSeparated($node->traits)
664              . (empty($node->adaptations)
665                 ? ';'
666                 : ' {' . $this->pStmts($node->adaptations) . $this->nl . '}');
667     }
668
669     protected function pStmt_TraitUseAdaptation_Precedence(Stmt\TraitUseAdaptation\Precedence $node) {
670         return $this->p($node->trait) . '::' . $node->method
671              . ' insteadof ' . $this->pCommaSeparated($node->insteadof) . ';';
672     }
673
674     protected function pStmt_TraitUseAdaptation_Alias(Stmt\TraitUseAdaptation\Alias $node) {
675         return (null !== $node->trait ? $this->p($node->trait) . '::' : '')
676              . $node->method . ' as'
677              . (null !== $node->newModifier ? ' ' . rtrim($this->pModifiers($node->newModifier), ' ') : '')
678              . (null !== $node->newName     ? ' ' . $node->newName                        : '')
679              . ';';
680     }
681
682     protected function pStmt_Property(Stmt\Property $node) {
683         return (0 === $node->flags ? 'var ' : $this->pModifiers($node->flags)) . $this->pCommaSeparated($node->props) . ';';
684     }
685
686     protected function pStmt_PropertyProperty(Stmt\PropertyProperty $node) {
687         return '$' . $node->name
688              . (null !== $node->default ? ' = ' . $this->p($node->default) : '');
689     }
690
691     protected function pStmt_ClassMethod(Stmt\ClassMethod $node) {
692         return $this->pModifiers($node->flags)
693              . 'function ' . ($node->byRef ? '&' : '') . $node->name
694              . '(' . $this->pCommaSeparated($node->params) . ')'
695              . (null !== $node->returnType ? ' : ' . $this->p($node->returnType) : '')
696              . (null !== $node->stmts
697                 ? $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}'
698                 : ';');
699     }
700
701     protected function pStmt_ClassConst(Stmt\ClassConst $node) {
702         return $this->pModifiers($node->flags)
703              . 'const ' . $this->pCommaSeparated($node->consts) . ';';
704     }
705
706     protected function pStmt_Function(Stmt\Function_ $node) {
707         return 'function ' . ($node->byRef ? '&' : '') . $node->name
708              . '(' . $this->pCommaSeparated($node->params) . ')'
709              . (null !== $node->returnType ? ' : ' . $this->p($node->returnType) : '')
710              . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
711     }
712
713     protected function pStmt_Const(Stmt\Const_ $node) {
714         return 'const ' . $this->pCommaSeparated($node->consts) . ';';
715     }
716
717     protected function pStmt_Declare(Stmt\Declare_ $node) {
718         return 'declare (' . $this->pCommaSeparated($node->declares) . ')'
719              . (null !== $node->stmts ? ' {' . $this->pStmts($node->stmts) . $this->nl . '}' : ';');
720     }
721
722     protected function pStmt_DeclareDeclare(Stmt\DeclareDeclare $node) {
723         return $node->key . '=' . $this->p($node->value);
724     }
725
726     // Control flow
727
728     protected function pStmt_If(Stmt\If_ $node) {
729         return 'if (' . $this->p($node->cond) . ') {'
730              . $this->pStmts($node->stmts) . $this->nl . '}'
731              . ($node->elseifs ? ' ' . $this->pImplode($node->elseifs, ' ') : '')
732              . (null !== $node->else ? ' ' . $this->p($node->else) : '');
733     }
734
735     protected function pStmt_ElseIf(Stmt\ElseIf_ $node) {
736         return 'elseif (' . $this->p($node->cond) . ') {'
737              . $this->pStmts($node->stmts) . $this->nl . '}';
738     }
739
740     protected function pStmt_Else(Stmt\Else_ $node) {
741         return 'else {' . $this->pStmts($node->stmts) . $this->nl . '}';
742     }
743
744     protected function pStmt_For(Stmt\For_ $node) {
745         return 'for ('
746              . $this->pCommaSeparated($node->init) . ';' . (!empty($node->cond) ? ' ' : '')
747              . $this->pCommaSeparated($node->cond) . ';' . (!empty($node->loop) ? ' ' : '')
748              . $this->pCommaSeparated($node->loop)
749              . ') {' . $this->pStmts($node->stmts) . $this->nl . '}';
750     }
751
752     protected function pStmt_Foreach(Stmt\Foreach_ $node) {
753         return 'foreach (' . $this->p($node->expr) . ' as '
754              . (null !== $node->keyVar ? $this->p($node->keyVar) . ' => ' : '')
755              . ($node->byRef ? '&' : '') . $this->p($node->valueVar) . ') {'
756              . $this->pStmts($node->stmts) . $this->nl . '}';
757     }
758
759     protected function pStmt_While(Stmt\While_ $node) {
760         return 'while (' . $this->p($node->cond) . ') {'
761              . $this->pStmts($node->stmts) . $this->nl . '}';
762     }
763
764     protected function pStmt_Do(Stmt\Do_ $node) {
765         return 'do {' . $this->pStmts($node->stmts) . $this->nl
766              . '} while (' . $this->p($node->cond) . ');';
767     }
768
769     protected function pStmt_Switch(Stmt\Switch_ $node) {
770         return 'switch (' . $this->p($node->cond) . ') {'
771              . $this->pStmts($node->cases) . $this->nl . '}';
772     }
773
774     protected function pStmt_Case(Stmt\Case_ $node) {
775         return (null !== $node->cond ? 'case ' . $this->p($node->cond) : 'default') . ':'
776              . $this->pStmts($node->stmts);
777     }
778
779     protected function pStmt_TryCatch(Stmt\TryCatch $node) {
780         return 'try {' . $this->pStmts($node->stmts) . $this->nl . '}'
781              . ($node->catches ? ' ' . $this->pImplode($node->catches, ' ') : '')
782              . ($node->finally !== null ? ' ' . $this->p($node->finally) : '');
783     }
784
785     protected function pStmt_Catch(Stmt\Catch_ $node) {
786         return 'catch (' . $this->pImplode($node->types, '|') . ' '
787              . $this->p($node->var)
788              . ') {' . $this->pStmts($node->stmts) . $this->nl . '}';
789     }
790
791     protected function pStmt_Finally(Stmt\Finally_ $node) {
792         return 'finally {' . $this->pStmts($node->stmts) . $this->nl . '}';
793     }
794
795     protected function pStmt_Break(Stmt\Break_ $node) {
796         return 'break' . ($node->num !== null ? ' ' . $this->p($node->num) : '') . ';';
797     }
798
799     protected function pStmt_Continue(Stmt\Continue_ $node) {
800         return 'continue' . ($node->num !== null ? ' ' . $this->p($node->num) : '') . ';';
801     }
802
803     protected function pStmt_Return(Stmt\Return_ $node) {
804         return 'return' . (null !== $node->expr ? ' ' . $this->p($node->expr) : '') . ';';
805     }
806
807     protected function pStmt_Throw(Stmt\Throw_ $node) {
808         return 'throw ' . $this->p($node->expr) . ';';
809     }
810
811     protected function pStmt_Label(Stmt\Label $node) {
812         return $node->name . ':';
813     }
814
815     protected function pStmt_Goto(Stmt\Goto_ $node) {
816         return 'goto ' . $node->name . ';';
817     }
818
819     // Other
820
821     protected function pStmt_Expression(Stmt\Expression $node) {
822         return $this->p($node->expr) . ';';
823     }
824
825     protected function pStmt_Echo(Stmt\Echo_ $node) {
826         return 'echo ' . $this->pCommaSeparated($node->exprs) . ';';
827     }
828
829     protected function pStmt_Static(Stmt\Static_ $node) {
830         return 'static ' . $this->pCommaSeparated($node->vars) . ';';
831     }
832
833     protected function pStmt_Global(Stmt\Global_ $node) {
834         return 'global ' . $this->pCommaSeparated($node->vars) . ';';
835     }
836
837     protected function pStmt_StaticVar(Stmt\StaticVar $node) {
838         return $this->p($node->var)
839              . (null !== $node->default ? ' = ' . $this->p($node->default) : '');
840     }
841
842     protected function pStmt_Unset(Stmt\Unset_ $node) {
843         return 'unset(' . $this->pCommaSeparated($node->vars) . ');';
844     }
845
846     protected function pStmt_InlineHTML(Stmt\InlineHTML $node) {
847         $newline = $node->getAttribute('hasLeadingNewline', true) ? "\n" : '';
848         return '?>' . $newline . $node->value . '<?php ';
849     }
850
851     protected function pStmt_HaltCompiler(Stmt\HaltCompiler $node) {
852         return '__halt_compiler();' . $node->remaining;
853     }
854
855     protected function pStmt_Nop(Stmt\Nop $node) {
856         return '';
857     }
858
859     // Helpers
860
861     protected function pClassCommon(Stmt\Class_ $node, $afterClassToken) {
862         return $this->pModifiers($node->flags)
863         . 'class' . $afterClassToken
864         . (null !== $node->extends ? ' extends ' . $this->p($node->extends) : '')
865         . (!empty($node->implements) ? ' implements ' . $this->pCommaSeparated($node->implements) : '')
866         . $this->nl . '{' . $this->pStmts($node->stmts) . $this->nl . '}';
867     }
868
869     protected function pObjectProperty($node) {
870         if ($node instanceof Expr) {
871             return '{' . $this->p($node) . '}';
872         } else {
873             return $node;
874         }
875     }
876
877     protected function pEncapsList(array $encapsList, $quote) {
878         $return = '';
879         foreach ($encapsList as $element) {
880             if ($element instanceof Scalar\EncapsedStringPart) {
881                 $return .= $this->escapeString($element->value, $quote);
882             } else {
883                 $return .= '{' . $this->p($element) . '}';
884             }
885         }
886
887         return $return;
888     }
889
890     protected function pSingleQuotedString(string $string) {
891         return '\'' . addcslashes($string, '\'\\') . '\'';
892     }
893
894     protected function escapeString($string, $quote) {
895         if (null === $quote) {
896             // For doc strings, don't escape newlines
897             $escaped = addcslashes($string, "\t\f\v$\\");
898         } else {
899             $escaped = addcslashes($string, "\n\r\t\f\v$" . $quote . "\\");
900         }
901
902         // Escape other control characters
903         return preg_replace_callback('/([\0-\10\16-\37])(?=([0-7]?))/', function ($matches) {
904             $oct = decoct(ord($matches[1]));
905             if ($matches[2] !== '') {
906                 // If there is a trailing digit, use the full three character form
907                 return '\\' . str_pad($oct, 3, '0', \STR_PAD_LEFT);
908             }
909             return '\\' . $oct;
910         }, $escaped);
911     }
912
913     protected function containsEndLabel($string, $label, $atStart = true, $atEnd = true) {
914         $start = $atStart ? '(?:^|[\r\n])' : '[\r\n]';
915         $end = $atEnd ? '(?:$|[;\r\n])' : '[;\r\n]';
916         return false !== strpos($string, $label)
917             && preg_match('/' . $start . $label . $end . '/', $string);
918     }
919
920     protected function encapsedContainsEndLabel(array $parts, $label) {
921         foreach ($parts as $i => $part) {
922             $atStart = $i === 0;
923             $atEnd = $i === count($parts) - 1;
924             if ($part instanceof Scalar\EncapsedStringPart
925                 && $this->containsEndLabel($part->value, $label, $atStart, $atEnd)
926             ) {
927                 return true;
928             }
929         }
930         return false;
931     }
932
933     protected function pDereferenceLhs(Node $node) {
934         if (!$this->dereferenceLhsRequiresParens($node)) {
935             return $this->p($node);
936         } else  {
937             return '(' . $this->p($node) . ')';
938         }
939     }
940
941     protected function pCallLhs(Node $node) {
942         if (!$this->callLhsRequiresParens($node)) {
943             return $this->p($node);
944         } else  {
945             return '(' . $this->p($node) . ')';
946         }
947     }
948
949     /**
950      * @param Node[] $nodes
951      * @return bool
952      */
953     private function hasNodeWithComments(array $nodes) {
954         foreach ($nodes as $node) {
955             if ($node && $node->getComments()) {
956                 return true;
957             }
958         }
959         return false;
960     }
961
962     private function pMaybeMultiline(array $nodes, $trailingComma = false) {
963         if (!$this->hasNodeWithComments($nodes)) {
964             return $this->pCommaSeparated($nodes);
965         } else {
966             return $this->pCommaSeparatedMultiline($nodes, $trailingComma) . $this->nl;
967         }
968     }
969 }