1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\PhpDocParser\Printer;
4:
5: use LogicException;
6: use PHPStan\PhpDocParser\Ast\Attribute;
7: use PHPStan\PhpDocParser\Ast\Comment;
8: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprArrayNode;
9: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprNode;
10: use PHPStan\PhpDocParser\Ast\Node;
11: use PHPStan\PhpDocParser\Ast\PhpDoc\AssertTagMethodValueNode;
12: use PHPStan\PhpDocParser\Ast\PhpDoc\AssertTagPropertyValueNode;
13: use PHPStan\PhpDocParser\Ast\PhpDoc\AssertTagValueNode;
14: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineAnnotation;
15: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArgument;
16: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArray;
17: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineArrayItem;
18: use PHPStan\PhpDocParser\Ast\PhpDoc\Doctrine\DoctrineTagValueNode;
19: use PHPStan\PhpDocParser\Ast\PhpDoc\ExtendsTagValueNode;
20: use PHPStan\PhpDocParser\Ast\PhpDoc\ImplementsTagValueNode;
21: use PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueNode;
22: use PHPStan\PhpDocParser\Ast\PhpDoc\MethodTagValueParameterNode;
23: use PHPStan\PhpDocParser\Ast\PhpDoc\MixinTagValueNode;
24: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamClosureThisTagValueNode;
25: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamImmediatelyInvokedCallableTagValueNode;
26: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamLaterInvokedCallableTagValueNode;
27: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamOutTagValueNode;
28: use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
29: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocChildNode;
30: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
31: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagNode;
32: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTagValueNode;
33: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
34: use PHPStan\PhpDocParser\Ast\PhpDoc\PropertyTagValueNode;
35: use PHPStan\PhpDocParser\Ast\PhpDoc\PureUnlessCallableIsImpureTagValueNode;
36: use PHPStan\PhpDocParser\Ast\PhpDoc\PureUnlessParameterIsPassedTagValueNode;
37: use PHPStan\PhpDocParser\Ast\PhpDoc\RequireExtendsTagValueNode;
38: use PHPStan\PhpDocParser\Ast\PhpDoc\RequireImplementsTagValueNode;
39: use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode;
40: use PHPStan\PhpDocParser\Ast\PhpDoc\SealedTagValueNode;
41: use PHPStan\PhpDocParser\Ast\PhpDoc\SelfOutTagValueNode;
42: use PHPStan\PhpDocParser\Ast\PhpDoc\TemplateTagValueNode;
43: use PHPStan\PhpDocParser\Ast\PhpDoc\ThrowsTagValueNode;
44: use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasImportTagValueNode;
45: use PHPStan\PhpDocParser\Ast\PhpDoc\TypeAliasTagValueNode;
46: use PHPStan\PhpDocParser\Ast\PhpDoc\UsesTagValueNode;
47: use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
48: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
49: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeNode;
50: use PHPStan\PhpDocParser\Ast\Type\ArrayShapeUnsealedTypeNode;
51: use PHPStan\PhpDocParser\Ast\Type\ArrayTypeNode;
52: use PHPStan\PhpDocParser\Ast\Type\CallableTypeNode;
53: use PHPStan\PhpDocParser\Ast\Type\CallableTypeParameterNode;
54: use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeForParameterNode;
55: use PHPStan\PhpDocParser\Ast\Type\ConditionalTypeNode;
56: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
57: use PHPStan\PhpDocParser\Ast\Type\GenericTypeNode;
58: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
59: use PHPStan\PhpDocParser\Ast\Type\IntersectionTypeNode;
60: use PHPStan\PhpDocParser\Ast\Type\InvalidTypeNode;
61: use PHPStan\PhpDocParser\Ast\Type\NameNode;
62: use PHPStan\PhpDocParser\Ast\Type\NullableTypeNode;
63: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode;
64: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
65: use PHPStan\PhpDocParser\Ast\Type\OffsetAccessTypeNode;
66: use PHPStan\PhpDocParser\Ast\Type\TemplateDeclarationTypeNode;
67: use PHPStan\PhpDocParser\Ast\Type\ThisTypeNode;
68: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
69: use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
70: use PHPStan\PhpDocParser\Lexer\Lexer;
71: use PHPStan\PhpDocParser\Parser\TokenIterator;
72: use function array_keys;
73: use function array_map;
74: use function array_values;
75: use function assert;
76: use function count;
77: use function get_class;
78: use function get_object_vars;
79: use function implode;
80: use function in_array;
81: use function is_array;
82: use function preg_match;
83: use function preg_match_all;
84: use function preg_replace_callback;
85: use function sprintf;
86: use function str_replace;
87: use function strlen;
88: use function strpos;
89: use function substr;
90: use function trim;
91: use const PREG_SET_ORDER;
92:
93: /**
94: * Inspired by https://github.com/nikic/PHP-Parser/tree/36a6dcd04e7b0285e8f0868f44bd4927802f7df1
95: *
96: * Copyright (c) 2011, Nikita Popov
97: * All rights reserved.
98: */
99: final class Printer
100: {
101:
102: /** @var Differ<Node> */
103: private Differ $differ;
104:
105: /**
106: * Newline, indentation and asterisk at the start of a PHPDoc line.
107: * Written after each newline in a printed text or description.
108: */
109: private string $lineStart = "\n *";
110:
111: /**
112: * Map From "{$class}->{$subNode}" to string that should be inserted
113: * between elements of this list subnode
114: *
115: * @var array<string, string>
116: */
117: private array $listInsertionMap = [
118: PhpDocNode::class . '->children' => "\n * ",
119: UnionTypeNode::class . '->types' => '|',
120: IntersectionTypeNode::class . '->types' => '&',
121: ArrayShapeNode::class . '->items' => ', ',
122: ObjectShapeNode::class . '->items' => ', ',
123: CallableTypeNode::class . '->parameters' => ', ',
124: CallableTypeNode::class . '->templateTypes' => ', ',
125: GenericTypeNode::class . '->genericTypes' => ', ',
126: ConstExprArrayNode::class . '->items' => ', ',
127: MethodTagValueNode::class . '->parameters' => ', ',
128: TypeAliasTagValueNode::class . '->templateTypes' => ', ',
129: DoctrineArray::class . '->items' => ', ',
130: DoctrineAnnotation::class . '->arguments' => ', ',
131: ];
132:
133: /**
134: * [$find, $extraLeft, $extraRight]
135: *
136: * @var array<string, array{string|null, string, string}>
137: */
138: private array $emptyListInsertionMap = [
139: CallableTypeNode::class . '->parameters' => ['(', '', ''],
140: ArrayShapeNode::class . '->items' => ['{', '', ''],
141: ObjectShapeNode::class . '->items' => ['{', '', ''],
142: DoctrineArray::class . '->items' => ['{', '', ''],
143: DoctrineAnnotation::class . '->arguments' => ['(', '', ''],
144: ];
145:
146: /** @var array<string, list<class-string<TypeNode>>> */
147: private array $parenthesesMap = [
148: CallableTypeNode::class . '->returnType' => [
149: CallableTypeNode::class,
150: UnionTypeNode::class,
151: IntersectionTypeNode::class,
152: ],
153: ArrayTypeNode::class . '->type' => [
154: CallableTypeNode::class,
155: UnionTypeNode::class,
156: IntersectionTypeNode::class,
157: ConstTypeNode::class,
158: NullableTypeNode::class,
159: ],
160: OffsetAccessTypeNode::class . '->type' => [
161: CallableTypeNode::class,
162: UnionTypeNode::class,
163: IntersectionTypeNode::class,
164: NullableTypeNode::class,
165: ],
166: NullableTypeNode::class . '->type' => [
167: UnionTypeNode::class,
168: IntersectionTypeNode::class,
169: NullableTypeNode::class,
170: ],
171: ConditionalTypeNode::class . '->subjectType' => [
172: UnionTypeNode::class,
173: IntersectionTypeNode::class,
174: NullableTypeNode::class,
175: ],
176: ];
177:
178: /** @var array<string, list<class-string<TypeNode>>> */
179: private array $parenthesesListMap = [
180: IntersectionTypeNode::class . '->types' => [
181: IntersectionTypeNode::class,
182: UnionTypeNode::class,
183: NullableTypeNode::class,
184: ],
185: UnionTypeNode::class . '->types' => [
186: IntersectionTypeNode::class,
187: UnionTypeNode::class,
188: NullableTypeNode::class,
189: ],
190: ];
191:
192: public function printFormatPreserving(PhpDocNode $node, PhpDocNode $originalNode, TokenIterator $originalTokens): string
193: {
194: $lineStart = $this->lineStart;
195: $this->lineStart = $this->detectLineStart($originalTokens);
196: try {
197: return $this->printFormatPreservingWithLineStart($node, $originalNode, $originalTokens);
198: } finally {
199: $this->lineStart = $lineStart;
200: }
201: }
202:
203: private function printFormatPreservingWithLineStart(PhpDocNode $node, PhpDocNode $originalNode, TokenIterator $originalTokens): string
204: {
205: $this->differ = new Differ(static function ($a, $b) {
206: if ($a instanceof Node && $b instanceof Node) {
207: return $a === $b->getAttribute(Attribute::ORIGINAL_NODE);
208: }
209:
210: return false;
211: });
212:
213: $tokenIndex = 0;
214: $result = $this->printArrayFormatPreserving(
215: $node->children,
216: $originalNode->children,
217: $originalTokens,
218: $tokenIndex,
219: PhpDocNode::class,
220: 'children',
221: );
222: if ($result !== null) {
223: return $result . $originalTokens->getContentBetween($tokenIndex, $originalTokens->getTokenCount());
224: }
225:
226: return $this->print($node);
227: }
228:
229: public function print(Node $node): string
230: {
231: if ($node instanceof PhpDocNode) {
232: return "/**\n *" . implode("\n *", array_map(
233: function (PhpDocChildNode $child): string {
234: $s = $this->addLineStarts($this->print($child));
235: return $s === '' ? '' : ' ' . $s;
236: },
237: $node->children,
238: )) . "\n */";
239: }
240: if ($node instanceof PhpDocTextNode) {
241: return $node->text;
242: }
243: if ($node instanceof PhpDocTagNode) {
244: if ($node->value instanceof DoctrineTagValueNode) {
245: return $this->print($node->value);
246: }
247:
248: return trim(sprintf('%s %s', $node->name, $this->print($node->value)));
249: }
250: if ($node instanceof PhpDocTagValueNode) {
251: return $this->printTagValue($node);
252: }
253: if ($node instanceof TypeNode) {
254: return $this->printType($node);
255: }
256: if ($node instanceof ConstExprNode) {
257: return $this->printConstExpr($node);
258: }
259: if ($node instanceof MethodTagValueParameterNode) {
260: $type = $node->type !== null ? $this->print($node->type) . ' ' : '';
261: $isReference = $node->isReference ? '&' : '';
262: $isVariadic = $node->isVariadic ? '...' : '';
263: $default = $node->defaultValue !== null ? ' = ' . $this->print($node->defaultValue) : '';
264: return "{$type}{$isReference}{$isVariadic}{$node->parameterName}{$default}";
265: }
266: if ($node instanceof CallableTypeParameterNode) {
267: $type = $this->print($node->type) . ' ';
268: $isReference = $node->isReference ? '&' : '';
269: $isVariadic = $node->isVariadic ? '...' : '';
270: $isOptional = $node->isOptional ? '=' : '';
271: return trim("{$type}{$isReference}{$isVariadic}{$node->parameterName}") . $isOptional;
272: }
273: if ($node instanceof ArrayShapeUnsealedTypeNode) {
274: if ($node->keyType !== null) {
275: return sprintf('<%s, %s>', $this->printType($node->keyType), $this->printType($node->valueType));
276: }
277: return sprintf('<%s>', $this->printType($node->valueType));
278: }
279: if ($node instanceof DoctrineAnnotation) {
280: return (string) $node;
281: }
282: if ($node instanceof DoctrineArgument) {
283: return (string) $node;
284: }
285: if ($node instanceof DoctrineArray) {
286: return (string) $node;
287: }
288: if ($node instanceof DoctrineArrayItem) {
289: return (string) $node;
290: }
291: if ($node instanceof ArrayShapeItemNode) {
292: if ($node->keyName !== null) {
293: return sprintf(
294: '%s%s: %s',
295: $this->print($node->keyName),
296: $node->optional ? '?' : '',
297: $this->printType($node->valueType),
298: );
299: }
300:
301: return $this->printType($node->valueType);
302: }
303: if ($node instanceof ObjectShapeItemNode) {
304: if ($node->keyName !== null) {
305: return sprintf(
306: '%s%s: %s',
307: $this->print($node->keyName),
308: $node->optional ? '?' : '',
309: $this->printType($node->valueType),
310: );
311: }
312:
313: return $this->printType($node->valueType);
314: }
315:
316: throw new LogicException(sprintf('Unknown node type %s', get_class($node)));
317: }
318:
319: private function printTagValue(PhpDocTagValueNode $node): string
320: {
321: // only nodes that contain another node are handled here
322: // the rest falls back on (string) $node
323:
324: if ($node instanceof AssertTagMethodValueNode) {
325: $isNegated = $node->isNegated ? '!' : '';
326: $isEquality = $node->isEquality ? '=' : '';
327: $type = $this->printType($node->type);
328: return trim("{$isNegated}{$isEquality}{$type} {$node->parameter}->{$node->method}() {$node->description}");
329: }
330: if ($node instanceof AssertTagPropertyValueNode) {
331: $isNegated = $node->isNegated ? '!' : '';
332: $isEquality = $node->isEquality ? '=' : '';
333: $type = $this->printType($node->type);
334: return trim("{$isNegated}{$isEquality}{$type} {$node->parameter}->{$node->property} {$node->description}");
335: }
336: if ($node instanceof AssertTagValueNode) {
337: $isNegated = $node->isNegated ? '!' : '';
338: $isEquality = $node->isEquality ? '=' : '';
339: $type = $this->printType($node->type);
340: return trim("{$isNegated}{$isEquality}{$type} {$node->parameter} {$node->description}");
341: }
342: if ($node instanceof ExtendsTagValueNode || $node instanceof ImplementsTagValueNode) {
343: $type = $this->printType($node->type);
344: return trim("{$type} {$node->description}");
345: }
346: if ($node instanceof MethodTagValueNode) {
347: $static = $node->isStatic ? 'static ' : '';
348: $returnType = $node->returnType !== null ? $this->printType($node->returnType) . ' ' : '';
349: $parameters = implode(', ', array_map(fn (MethodTagValueParameterNode $parameter): string => $this->print($parameter), $node->parameters));
350: $description = $node->description !== '' ? " {$node->description}" : '';
351: $templateTypes = count($node->templateTypes) > 0 ? '<' . implode(', ', array_map(fn (TemplateTagValueNode $templateTag): string => $this->print($templateTag), $node->templateTypes)) . '>' : '';
352: return "{$static}{$returnType}{$node->methodName}{$templateTypes}({$parameters}){$description}";
353: }
354: if ($node instanceof MixinTagValueNode) {
355: $type = $this->printType($node->type);
356: return trim("{$type} {$node->description}");
357: }
358: if ($node instanceof RequireExtendsTagValueNode) {
359: $type = $this->printType($node->type);
360: return trim("{$type} {$node->description}");
361: }
362: if ($node instanceof RequireImplementsTagValueNode) {
363: $type = $this->printType($node->type);
364: return trim("{$type} {$node->description}");
365: }
366: if ($node instanceof SealedTagValueNode) {
367: $type = $this->printType($node->type);
368: return trim("{$type} {$node->description}");
369: }
370: if ($node instanceof ParamOutTagValueNode) {
371: $type = $this->printType($node->type);
372: return trim("{$type} {$node->parameterName} {$node->description}");
373: }
374: if ($node instanceof ParamTagValueNode) {
375: $reference = $node->isReference ? '&' : '';
376: $variadic = $node->isVariadic ? '...' : '';
377: $type = $this->printType($node->type);
378: return trim("{$type} {$reference}{$variadic}{$node->parameterName} {$node->description}");
379: }
380: if ($node instanceof ParamImmediatelyInvokedCallableTagValueNode) {
381: return trim("{$node->parameterName} {$node->description}");
382: }
383: if ($node instanceof ParamLaterInvokedCallableTagValueNode) {
384: return trim("{$node->parameterName} {$node->description}");
385: }
386: if ($node instanceof ParamClosureThisTagValueNode) {
387: return trim("{$node->type} {$node->parameterName} {$node->description}");
388: }
389: if ($node instanceof PureUnlessCallableIsImpureTagValueNode) {
390: return trim("{$node->parameterName} {$node->description}");
391: }
392: if ($node instanceof PureUnlessParameterIsPassedTagValueNode) {
393: return trim("{$node->parameterName} {$node->description}");
394: }
395: if ($node instanceof PropertyTagValueNode) {
396: $type = $this->printType($node->type);
397: return trim("{$type} {$node->propertyName} {$node->description}");
398: }
399: if ($node instanceof ReturnTagValueNode) {
400: $type = $this->printType($node->type);
401: return trim("{$type} {$node->description}");
402: }
403: if ($node instanceof SelfOutTagValueNode) {
404: $type = $this->printType($node->type);
405: return trim($type . ' ' . $node->description);
406: }
407: if ($node instanceof TemplateTagValueNode) {
408: $upperBound = $node->bound !== null ? ' of ' . $this->printType($node->bound) : '';
409: $lowerBound = $node->lowerBound !== null ? ' super ' . $this->printType($node->lowerBound) : '';
410: $default = $node->default !== null ? ' = ' . $this->printType($node->default) : '';
411: return trim("{$node->name}{$upperBound}{$lowerBound}{$default} {$node->description}");
412: }
413: if ($node instanceof ThrowsTagValueNode) {
414: $type = $this->printType($node->type);
415: return trim("{$type} {$node->description}");
416: }
417: if ($node instanceof TypeAliasImportTagValueNode) {
418: return trim(
419: "{$node->importedAlias} from " . $this->printType($node->importedFrom)
420: . ($node->importedAs !== null ? " as {$node->importedAs}" : ''),
421: );
422: }
423: if ($node instanceof TypeAliasTagValueNode) {
424: $templateTypes = $node->templateTypes !== []
425: ? '<' . implode(', ', array_map(fn (TemplateTagValueNode $templateNode): string => $this->print($templateNode), $node->templateTypes)) . '>'
426: : '';
427: $type = $this->printType($node->type);
428: return trim("{$node->alias}{$templateTypes} {$type}");
429: }
430: if ($node instanceof UsesTagValueNode) {
431: $type = $this->printType($node->type);
432: return trim("{$type} {$node->description}");
433: }
434: if ($node instanceof VarTagValueNode) {
435: $type = $this->printType($node->type);
436: return trim("{$type} " . trim("{$node->variableName} {$node->description}"));
437: }
438:
439: return (string) $node;
440: }
441:
442: private function printType(TypeNode $node): string
443: {
444: if ($node instanceof ArrayShapeNode) {
445: $items = array_map(fn (ArrayShapeItemNode $item): string => $this->print($item), $node->items);
446:
447: if (! $node->sealed) {
448: $items[] = '...' . ($node->unsealedType === null ? '' : $this->print($node->unsealedType));
449: }
450:
451: return $node->kind . '{' . implode(', ', $items) . '}';
452: }
453: if ($node instanceof ArrayTypeNode) {
454: return $this->printOffsetAccessType($node->type) . '[]';
455: }
456: if ($node instanceof CallableTypeNode) {
457: if ($node->returnType instanceof CallableTypeNode || $node->returnType instanceof UnionTypeNode || $node->returnType instanceof IntersectionTypeNode) {
458: $returnType = $this->wrapInParentheses($node->returnType);
459: } else {
460: $returnType = $this->printType($node->returnType);
461: }
462: $template = $node->templateTypes !== []
463: ? '<' . implode(', ', array_map(fn (TemplateTagValueNode $templateNode): string => $this->print($templateNode), $node->templateTypes)) . '>'
464: : '';
465: $parameters = implode(', ', array_map(fn (CallableTypeParameterNode $parameterNode): string => $this->print($parameterNode), $node->parameters));
466: return $this->printType($node->identifier) . "{$template}({$parameters}): {$returnType}";
467: }
468: if ($node instanceof ConditionalTypeForParameterNode) {
469: return sprintf(
470: '(%s %s %s ? %s : %s)',
471: $node->parameterName,
472: $node->negated ? 'is not' : 'is',
473: $this->printType($node->targetType),
474: $this->printType($node->if),
475: $this->printType($node->else),
476: );
477: }
478: if ($node instanceof ConditionalTypeNode) {
479: return sprintf(
480: '(%s %s %s ? %s : %s)',
481: $this->printConditionalSubjectType($node->subjectType),
482: $node->negated ? 'is not' : 'is',
483: $this->printType($node->targetType),
484: $this->printType($node->if),
485: $this->printType($node->else),
486: );
487: }
488: if ($node instanceof ConstTypeNode) {
489: return $this->printConstExpr($node->constExpr);
490: }
491: if ($node instanceof GenericTypeNode) {
492: $genericTypes = [];
493:
494: foreach ($node->genericTypes as $index => $type) {
495: $variance = $node->variances[$index] ?? GenericTypeNode::VARIANCE_INVARIANT;
496: if ($variance === GenericTypeNode::VARIANCE_INVARIANT) {
497: $genericTypes[] = $this->printType($type);
498: } elseif ($variance === GenericTypeNode::VARIANCE_BIVARIANT) {
499: $genericTypes[] = '*';
500: } else {
501: $genericTypes[] = sprintf('%s %s', $variance, $this->print($type));
502: }
503: }
504:
505: return $this->printType($node->type) . '<' . implode(', ', $genericTypes) . '>';
506: }
507: if ($node instanceof IdentifierTypeNode) {
508: return $node->name;
509: }
510: if ($node instanceof TemplateDeclarationTypeNode) {
511: return $node->name . ' of ' . $this->printType($node->bound);
512: }
513: if ($node instanceof NameNode) {
514: return $node->toCodeString();
515: }
516: if ($node instanceof IntersectionTypeNode || $node instanceof UnionTypeNode) {
517: $items = [];
518: foreach ($node->types as $type) {
519: if (
520: $type instanceof IntersectionTypeNode
521: || $type instanceof UnionTypeNode
522: || $type instanceof NullableTypeNode
523: ) {
524: $items[] = $this->wrapInParentheses($type);
525: continue;
526: }
527:
528: $items[] = $this->printType($type);
529: }
530:
531: return implode($node instanceof IntersectionTypeNode ? '&' : '|', $items);
532: }
533: if ($node instanceof InvalidTypeNode) {
534: return (string) $node;
535: }
536: if ($node instanceof NullableTypeNode) {
537: if (
538: $node->type instanceof IntersectionTypeNode
539: || $node->type instanceof UnionTypeNode
540: || $node->type instanceof NullableTypeNode
541: ) {
542: return '?(' . $this->printType($node->type) . ')';
543: }
544:
545: return '?' . $this->printType($node->type);
546: }
547: if ($node instanceof ObjectShapeNode) {
548: $items = array_map(fn (ObjectShapeItemNode $item): string => $this->print($item), $node->items);
549:
550: return 'object{' . implode(', ', $items) . '}';
551: }
552: if ($node instanceof OffsetAccessTypeNode) {
553: return $this->printOffsetAccessType($node->type) . '[' . $this->printType($node->offset) . ']';
554: }
555: if ($node instanceof ThisTypeNode) {
556: return (string) $node;
557: }
558:
559: throw new LogicException(sprintf('Unknown node type %s', get_class($node)));
560: }
561:
562: private function wrapInParentheses(TypeNode $node): string
563: {
564: return '(' . $this->printType($node) . ')';
565: }
566:
567: /**
568: * What a conditional type asks about, written so that it is read back as
569: * the very same type.
570: *
571: * "?Foo is Bar ? ... : ..." and "Foo|Bar is Baz ? ... : ..." both read as a
572: * type followed by something the type says nothing about, so a subject of
573: * either kind keeps its parentheses.
574: */
575: private function printConditionalSubjectType(TypeNode $type): string
576: {
577: if (
578: $type instanceof UnionTypeNode
579: || $type instanceof IntersectionTypeNode
580: || $type instanceof NullableTypeNode
581: ) {
582: return $this->wrapInParentheses($type);
583: }
584:
585: return $this->printType($type);
586: }
587:
588: private function printOffsetAccessType(TypeNode $type): string
589: {
590: if (
591: $type instanceof CallableTypeNode
592: || $type instanceof UnionTypeNode
593: || $type instanceof IntersectionTypeNode
594: || $type instanceof NullableTypeNode
595: ) {
596: return $this->wrapInParentheses($type);
597: }
598:
599: return $this->printType($type);
600: }
601:
602: private function printConstExpr(ConstExprNode $node): string
603: {
604: // this is fine - ConstExprNode classes do not contain nodes that need smart printer logic
605: return (string) $node;
606: }
607:
608: /**
609: * @param Node[] $nodes
610: * @param Node[] $originalNodes
611: */
612: private function printArrayFormatPreserving(array $nodes, array $originalNodes, TokenIterator $originalTokens, int &$tokenIndex, string $parentNodeClass, string $subNodeName): ?string
613: {
614: // unset() leaves gaps in the keys, the differ reads the lists by position
615: $nodes = array_values($nodes);
616: $originalNodes = array_values($originalNodes);
617:
618: $diff = $this->differ->diffWithReplacements($originalNodes, $nodes);
619: $mapKey = $parentNodeClass . '->' . $subNodeName;
620: $insertStr = $this->listInsertionMap[$mapKey] ?? null;
621: $result = '';
622: $beforeFirstKeepOrReplace = true;
623: $skipRemovedNode = false;
624: $delayedAdd = [];
625:
626: $insertNewline = false;
627: [$isMultiline, $beforeAsteriskIndent, $afterAsteriskIndent] = $this->isMultiline($tokenIndex, $originalNodes, $originalTokens);
628:
629: if ($insertStr === "\n * ") {
630: $lastChildIndent = $this->detectLastChildIndent($originalNodes, $originalTokens);
631: if ($lastChildIndent !== null) {
632: [$beforeAsteriskIndent, $afterAsteriskIndent] = $lastChildIndent;
633: }
634:
635: $insertStr = sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
636: }
637:
638: foreach ($diff as $i => $diffElem) {
639: $diffType = $diffElem->type;
640: $arrItem = $diffElem->new;
641: $origArrayItem = $diffElem->old;
642: if ($diffType === DiffElem::TYPE_KEEP || $diffType === DiffElem::TYPE_REPLACE) {
643: $beforeFirstKeepOrReplace = false;
644: if (!$arrItem instanceof Node || !$origArrayItem instanceof Node) {
645: return null;
646: }
647:
648: /** @var int $itemStartPos */
649: $itemStartPos = $origArrayItem->getAttribute(Attribute::START_INDEX);
650:
651: /** @var int $itemEndPos */
652: $itemEndPos = $origArrayItem->getAttribute(Attribute::END_INDEX);
653:
654: if ($itemStartPos < 0 || $itemEndPos < 0 || $itemStartPos < $tokenIndex) {
655: throw new LogicException();
656: }
657:
658: $comments = $arrItem->getAttribute(Attribute::COMMENTS) ?? [];
659: $origComments = $origArrayItem->getAttribute(Attribute::COMMENTS) ?? [];
660:
661: $commentStartPos = count($origComments) > 0 ? $origComments[0]->startIndex : $itemStartPos;
662: assert($commentStartPos >= 0);
663:
664: if ($skipRemovedNode) {
665: // the separator after the removed first item belongs to it
666: $skipRemovedNode = false;
667: } else {
668: $result .= $originalTokens->getContentBetween($tokenIndex, $itemStartPos);
669: }
670:
671: if (count($delayedAdd) > 0) {
672: foreach ($delayedAdd as $delayedAddNode) {
673: $parenthesesNeeded = isset($this->parenthesesListMap[$mapKey])
674: && in_array(get_class($delayedAddNode), $this->parenthesesListMap[$mapKey], true);
675: if ($parenthesesNeeded) {
676: $result .= '(';
677: }
678:
679: if ($insertNewline) {
680: $delayedAddComments = $delayedAddNode->getAttribute(Attribute::COMMENTS) ?? [];
681: if (count($delayedAddComments) > 0) {
682: $result .= $this->printComments($delayedAddComments, $beforeAsteriskIndent, $afterAsteriskIndent);
683: $result .= sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
684: }
685: }
686:
687: $result = $this->appendNode($result, $this->printNodeFormatPreserving($delayedAddNode, $originalTokens), $afterAsteriskIndent);
688: if ($parenthesesNeeded) {
689: $result .= ')';
690: }
691:
692: if ($insertNewline) {
693: $result .= $insertStr . sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
694: } else {
695: $result .= $insertStr;
696: }
697: }
698:
699: $delayedAdd = [];
700: }
701:
702: $parenthesesNeeded = isset($this->parenthesesListMap[$mapKey])
703: && in_array(get_class($arrItem), $this->parenthesesListMap[$mapKey], true)
704: && !in_array(get_class($origArrayItem), $this->parenthesesListMap[$mapKey], true);
705: $addParentheses = $parenthesesNeeded && !$originalTokens->hasParentheses($itemStartPos, $itemEndPos);
706: if ($addParentheses) {
707: $result .= '(';
708: }
709:
710: if ($comments !== $origComments) {
711: if (count($comments) > 0) {
712: $result .= $this->printComments($comments, $beforeAsteriskIndent, $afterAsteriskIndent);
713: $result .= sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
714: }
715: }
716:
717: $result .= $this->printNodeFormatPreserving($arrItem, $originalTokens);
718: if ($addParentheses) {
719: $result .= ')';
720: }
721: $tokenIndex = $itemEndPos + 1;
722:
723: } elseif ($diffType === DiffElem::TYPE_ADD) {
724: if ($insertStr === null) {
725: return null;
726: }
727: if (!$arrItem instanceof Node) {
728: return null;
729: }
730:
731: if ($insertStr === ', ' && $isMultiline || count($arrItem->getAttribute(Attribute::COMMENTS) ?? []) > 0) {
732: $insertStr = ',';
733: $insertNewline = true;
734: }
735:
736: if ($beforeFirstKeepOrReplace) {
737: // Will be inserted at the next "replace" or "keep" element
738: $delayedAdd[] = $arrItem;
739: continue;
740: }
741:
742: /** @var int $itemEndPos */
743: $itemEndPos = $tokenIndex - 1;
744: if ($insertNewline) {
745: $comments = $arrItem->getAttribute(Attribute::COMMENTS) ?? [];
746: $result .= $insertStr;
747: if (count($comments) > 0) {
748: $result .= sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
749: $result .= $this->printComments($comments, $beforeAsteriskIndent, $afterAsteriskIndent);
750: }
751: $result .= sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
752: } else {
753: $result .= $insertStr;
754: }
755:
756: $parenthesesNeeded = isset($this->parenthesesListMap[$mapKey])
757: && in_array(get_class($arrItem), $this->parenthesesListMap[$mapKey], true);
758: if ($parenthesesNeeded) {
759: $result .= '(';
760: }
761:
762: $result = $this->appendNode($result, $this->printNodeFormatPreserving($arrItem, $originalTokens), $afterAsteriskIndent);
763: if ($parenthesesNeeded) {
764: $result .= ')';
765: }
766:
767: $tokenIndex = $itemEndPos + 1;
768:
769: } elseif ($diffType === DiffElem::TYPE_REMOVE) {
770: if (!$origArrayItem instanceof Node) {
771: return null;
772: }
773:
774: /** @var int $itemStartPos */
775: $itemStartPos = $origArrayItem->getAttribute(Attribute::START_INDEX);
776:
777: /** @var int $itemEndPos */
778: $itemEndPos = $origArrayItem->getAttribute(Attribute::END_INDEX);
779: if ($itemStartPos < 0 || $itemEndPos < 0) {
780: throw new LogicException();
781: }
782:
783: if ($i === 0) {
784: // If we're removing from the start, keep the tokens before the node and drop those after it,
785: // instead of the other way around.
786: if ($mapKey === PhpDocNode::class . '->children') {
787: // the line of the removed child is dropped, the next child keeps its own line
788: $originalTokensArray = $originalTokens->getTokens();
789: for ($j = $tokenIndex; $j < $itemStartPos; $j++) {
790: if ($originalTokensArray[$j][Lexer::TYPE_OFFSET] === Lexer::TOKEN_PHPDOC_EOL) {
791: break;
792: }
793: $result .= $originalTokensArray[$j][Lexer::VALUE_OFFSET];
794: }
795: } else {
796: $result .= $originalTokens->getContentBetween($tokenIndex, $itemStartPos);
797: $skipRemovedNode = true;
798: }
799: }
800:
801: $tokenIndex = $itemEndPos + 1;
802: }
803: }
804:
805: if (count($delayedAdd) > 0) {
806: if (!isset($this->emptyListInsertionMap[$mapKey])) {
807: return null;
808: }
809:
810: [$findToken, $extraLeft, $extraRight] = $this->emptyListInsertionMap[$mapKey];
811: if ($findToken !== null) {
812: $originalTokensArray = $originalTokens->getTokens();
813: for (; $tokenIndex < count($originalTokensArray); $tokenIndex++) {
814: $result .= $originalTokensArray[$tokenIndex][Lexer::VALUE_OFFSET];
815: if ($originalTokensArray[$tokenIndex][Lexer::VALUE_OFFSET] !== $findToken) {
816: continue;
817: }
818:
819: $tokenIndex++;
820: break;
821: }
822: }
823: $first = true;
824: $result .= $extraLeft;
825: foreach ($delayedAdd as $delayedAddNode) {
826: if (!$first) {
827: $result .= $insertStr;
828: if ($insertNewline) {
829: $result .= sprintf('%s%s*%s', $originalTokens->getDetectedNewline() ?? "\n", $beforeAsteriskIndent, $afterAsteriskIndent);
830: }
831: }
832:
833: $result = $this->appendNode($result, $this->printNodeFormatPreserving($delayedAddNode, $originalTokens), $afterAsteriskIndent);
834: $first = false;
835: }
836: $result .= $extraRight;
837: }
838:
839: return $result;
840: }
841:
842: /**
843: * A new empty line in a docblock is " *", without the space after the asterisk
844: */
845: private function appendNode(string $result, string $printedNode, string $afterAsteriskIndent): string
846: {
847: $lineStart = '*' . $afterAsteriskIndent;
848: if ($printedNode !== '' || $afterAsteriskIndent === '' || substr($result, -strlen($lineStart)) !== $lineStart) {
849: return $result . $printedNode;
850: }
851:
852: return substr($result, 0, -strlen($afterAsteriskIndent));
853: }
854:
855: /**
856: * @param list<Comment> $comments
857: */
858: private function printComments(array $comments, string $beforeAsteriskIndent, string $afterAsteriskIndent): string
859: {
860: $formattedComments = [];
861:
862: foreach ($comments as $comment) {
863: $formattedComments[] = str_replace("\n", "\n" . $beforeAsteriskIndent . '*' . $afterAsteriskIndent, $comment->getReformattedText());
864: }
865:
866: return implode("\n$beforeAsteriskIndent*$afterAsteriskIndent", $formattedComments);
867: }
868:
869: /**
870: * @param array<Node|null> $nodes
871: * @return array{bool, string, string}
872: */
873: private function isMultiline(int $initialIndex, array $nodes, TokenIterator $originalTokens): array
874: {
875: $isMultiline = count($nodes) > 1;
876: $pos = $initialIndex;
877: $allText = '';
878: /** @var Node|null $node */
879: foreach ($nodes as $node) {
880: if (!$node instanceof Node) {
881: continue;
882: }
883:
884: $endPos = $node->getAttribute(Attribute::END_INDEX) + 1;
885: $text = $originalTokens->getContentBetween($pos, $endPos);
886: $allText .= $text;
887: if (strpos($text, "\n") === false) {
888: // We require that a newline is present between *every* item. If the formatting
889: // is inconsistent, with only some items having newlines, we don't consider it
890: // as multiline
891: $isMultiline = false;
892: }
893: $pos = $endPos;
894: }
895:
896: $c = preg_match_all('~\n(?<before>[\\x09\\x20]*)\*(?<after>\\x20*)~', $allText, $matches, PREG_SET_ORDER);
897: if ($c === 0) {
898: return [$isMultiline, ' ', ' '];
899: }
900:
901: $before = '';
902: $after = '';
903: foreach ($matches as $match) {
904: if (strlen($match['before']) > strlen($before)) {
905: $before = $match['before'];
906: }
907: if (strlen($match['after']) <= strlen($after)) {
908: continue;
909: }
910:
911: $after = $match['after'];
912: }
913:
914: $before = strlen($before) === 0 ? ' ' : $before;
915: $after = strlen($after) === 0 ? ' ' : $after;
916:
917: return [$isMultiline, $before, $after];
918: }
919:
920: /**
921: * Indentation before and after the asterisk on the line where the last child of a PHPDoc starts.
922: * Other lines, e.g. the next lines of a multi-line description, can have a different indentation.
923: *
924: * @param Node[] $originalNodes
925: * @return array{string, string}|null
926: */
927: private function detectLastChildIndent(array $originalNodes, TokenIterator $originalTokens): ?array
928: {
929: $tokens = $originalTokens->getTokens();
930: for ($i = count($originalNodes) - 1; $i >= 0; $i--) {
931: $index = $originalNodes[$i]->getAttribute(Attribute::START_INDEX) - 1;
932: $lineStart = '';
933: while (isset($tokens[$index]) && $tokens[$index][Lexer::TYPE_OFFSET] === Lexer::TOKEN_HORIZONTAL_WS) {
934: $lineStart = $tokens[$index][Lexer::VALUE_OFFSET] . $lineStart;
935: $index--;
936: }
937:
938: if (!isset($tokens[$index]) || $tokens[$index][Lexer::TYPE_OFFSET] !== Lexer::TOKEN_PHPDOC_EOL) {
939: continue;
940: }
941:
942: $lineStart = $tokens[$index][Lexer::VALUE_OFFSET] . $lineStart;
943: if (preg_match('~\n(?<before>[\x09\x20]*)\*(?<after>[\x09\x20]*)$~', $lineStart, $match) !== 1) {
944: continue;
945: }
946:
947: return [$match['before'], $match['after']];
948: }
949:
950: return null;
951: }
952:
953: private function printNodeFormatPreserving(Node $node, TokenIterator $originalTokens): string
954: {
955: /** @var Node|null $originalNode */
956: $originalNode = $node->getAttribute(Attribute::ORIGINAL_NODE);
957: if ($originalNode === null) {
958: return $this->printReplacement($node);
959: }
960:
961: $class = get_class($node);
962: if ($class !== get_class($originalNode)) {
963: throw new LogicException();
964: }
965:
966: $startPos = $originalNode->getAttribute(Attribute::START_INDEX);
967: $endPos = $originalNode->getAttribute(Attribute::END_INDEX);
968: if ($startPos < 0 || $endPos < 0) {
969: throw new LogicException();
970: }
971:
972: $result = '';
973: $pos = $startPos;
974: $subNodeNames = array_keys(get_object_vars($node));
975: foreach ($subNodeNames as $subNodeName) {
976: $subNode = $node->$subNodeName;
977: $origSubNode = $originalNode->$subNodeName;
978:
979: if (
980: (!$subNode instanceof Node && $subNode !== null)
981: || (!$origSubNode instanceof Node && $origSubNode !== null)
982: ) {
983: if ($subNode === $origSubNode) {
984: // Unchanged, can reuse old code
985: continue;
986: }
987:
988: if ($this->isRenamedTag($node, $subNodeName, $originalTokens, $startPos)) {
989: // the tag name is the first token of the tag; keep the format of the value
990: $result .= $subNode;
991: $pos = $startPos + 1;
992: continue;
993: }
994:
995: if (
996: $node instanceof DoctrineAnnotation
997: && $subNodeName === 'name'
998: && $node->getAttribute(Attribute::ORIGINAL_NODE)->name !== $originalTokens->getContentBetween($startPos, $startPos + 1)
999: ) {
1000: // the tokens of the annotation of a Doctrine tag do not contain the name, the tag prints it
1001: continue;
1002: }
1003:
1004: if (is_array($subNode) && is_array($origSubNode)) {
1005: // Array subnode changed, we might be able to reconstruct it
1006: $listResult = $this->printArrayFormatPreserving(
1007: $subNode,
1008: $origSubNode,
1009: $originalTokens,
1010: $pos,
1011: $class,
1012: $subNodeName,
1013: );
1014:
1015: if ($listResult === null) {
1016: return $this->printReplacement($node);
1017: }
1018:
1019: $result .= $listResult;
1020: continue;
1021: }
1022:
1023: return $this->printReplacement($node);
1024: }
1025:
1026: if ($origSubNode === null) {
1027: if ($subNode === null) {
1028: // Both null, nothing to do
1029: continue;
1030: }
1031:
1032: return $this->printReplacement($node);
1033: }
1034:
1035: $subStartPos = $origSubNode->getAttribute(Attribute::START_INDEX);
1036: $subEndPos = $origSubNode->getAttribute(Attribute::END_INDEX);
1037: if ($subStartPos < 0 || $subEndPos < 0) {
1038: throw new LogicException();
1039: }
1040:
1041: if ($subEndPos < $subStartPos) {
1042: // the original sub-node has no tokens, e.g. a Doctrine annotation without arguments
1043: if ($subNode !== null && $this->print($subNode) === $this->print($origSubNode)) {
1044: continue;
1045: }
1046:
1047: return $this->printReplacement($node);
1048: }
1049:
1050: if ($subNode === null) {
1051: return $this->printReplacement($node);
1052: }
1053:
1054: $result .= $originalTokens->getContentBetween($pos, $subStartPos);
1055: $mapKey = get_class($node) . '->' . $subNodeName;
1056: $parenthesesNeeded = isset($this->parenthesesMap[$mapKey])
1057: && in_array(get_class($subNode), $this->parenthesesMap[$mapKey], true);
1058:
1059: if ($subNode->getAttribute(Attribute::ORIGINAL_NODE) !== null) {
1060: $parenthesesNeeded = $parenthesesNeeded
1061: && !in_array(get_class($subNode->getAttribute(Attribute::ORIGINAL_NODE)), $this->parenthesesMap[$mapKey], true);
1062: }
1063:
1064: $addParentheses = $parenthesesNeeded && !$originalTokens->hasParentheses($subStartPos, $subEndPos);
1065: if ($addParentheses) {
1066: $result .= '(';
1067: }
1068:
1069: $result .= $this->printNodeFormatPreserving($subNode, $originalTokens);
1070: if ($addParentheses) {
1071: $result .= ')';
1072: }
1073:
1074: $pos = $subEndPos + 1;
1075: }
1076:
1077: return $result . $originalTokens->getContentBetween($pos, $endPos + 1);
1078: }
1079:
1080: private function isRenamedTag(Node $node, string $subNodeName, TokenIterator $originalTokens, int $startPos): bool
1081: {
1082: if (!$node instanceof PhpDocTagNode || $subNodeName !== 'name') {
1083: return false;
1084: }
1085:
1086: $originalNode = $node->getAttribute(Attribute::ORIGINAL_NODE);
1087: if (!$originalNode instanceof PhpDocTagNode) {
1088: return false;
1089: }
1090:
1091: return $originalTokens->getContentBetween($startPos, $startPos + 1) === $originalNode->name;
1092: }
1093:
1094: /**
1095: * Prints a node that replaces the tokens of the original node.
1096: *
1097: * The tokens of a Doctrine tag value do not contain the annotation name.
1098: * The parent tag prints the name from its own tokens.
1099: */
1100: private function printReplacement(Node $node): string
1101: {
1102: if (!$node instanceof DoctrineTagValueNode) {
1103: return $this->addLineStarts($this->print($node));
1104: }
1105:
1106: $arguments = '(' . implode(', ', $node->annotation->arguments) . ')';
1107: if ($node->annotation->arguments === []) {
1108: $originalNode = $node->getAttribute(Attribute::ORIGINAL_NODE);
1109: if (
1110: $originalNode instanceof DoctrineTagValueNode
1111: && $originalNode->annotation->getAttribute(Attribute::END_INDEX) < $originalNode->annotation->getAttribute(Attribute::START_INDEX)
1112: ) {
1113: $arguments = '';
1114: }
1115: }
1116:
1117: return $this->addLineStarts(trim($arguments . ' ' . $node->description));
1118: }
1119:
1120: /**
1121: * The parser removes the asterisk at the start of each line of a text or description.
1122: * This puts it back.
1123: */
1124: private function addLineStarts(string $s): string
1125: {
1126: return preg_replace_callback(
1127: '~\r?\n(?=(.?))~',
1128: fn (array $matches): string => $matches[1] === '' || $matches[1] === "\r" || $matches[1] === "\n"
1129: ? $this->lineStart
1130: : $this->lineStart . ' ',
1131: $s,
1132: ) ?? $s;
1133: }
1134:
1135: private function detectLineStart(TokenIterator $originalTokens): string
1136: {
1137: foreach ($originalTokens->getTokens() as $token) {
1138: if ($token[Lexer::TYPE_OFFSET] !== Lexer::TOKEN_PHPDOC_EOL) {
1139: continue;
1140: }
1141:
1142: $asteriskPosition = strpos($token[Lexer::VALUE_OFFSET], '*');
1143: if ($asteriskPosition === false) {
1144: continue;
1145: }
1146:
1147: return substr($token[Lexer::VALUE_OFFSET], 0, $asteriskPosition + 1);
1148: }
1149:
1150: return ($originalTokens->getDetectedNewline() ?? "\n") . ' *';
1151: }
1152:
1153: }
1154: