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