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