Repository navigation
Expand file tree
/
Copy pathBetterStandardPrinter.php
More file actions
667 lines (559 loc) · 21.7 KB
/
Copy pathBetterStandardPrinter.php
File metadata and controls
667 lines (559 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
<?php
declare(strict_types=1);
namespace Rector\PhpParser\Printer;
use Nette\Utils\Strings;
use PhpParser\Comment;
use PhpParser\Internal\TokenStream;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignOp;
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\BinaryOp\BooleanOr;
use PhpParser\Node\Expr\BinaryOp\Pipe;
use PhpParser\Node\Expr\CallLike;
use PhpParser\Node\Expr\Instanceof_;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\Print_;
use PhpParser\Node\Expr\Ternary;
use PhpParser\Node\Expr\Yield_;
use PhpParser\Node\Expr\YieldFrom;
use PhpParser\Node\InterpolatedStringPart;
use PhpParser\Node\Scalar\InterpolatedString;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Declare_;
use PhpParser\Node\Stmt\Enum_;
use PhpParser\Node\Stmt\InlineHTML;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Nop;
use PhpParser\PrettyPrinter\Standard;
use PhpParser\Token;
use Rector\Configuration\Option;
use Rector\Configuration\Parameter\SimpleParameterProvider;
use Rector\NodeAnalyzer\ExprAnalyzer;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpParser\Node\FileNode;
use Rector\Util\NewLineSplitter;
use Rector\Util\Reflection\PrivatesAccessor;
/**
* @see \Rector\Tests\PhpParser\Printer\BetterStandardPrinterTest
*
* @property array<string, array{string, bool, string, null}> $insertionMap
*/
final class BetterStandardPrinter extends Standard
{
/**
* Remove extra spaces before new Nop_ nodes
* @see https://regex101.com/r/iSvroO/1
*/
private const string EXTRA_SPACE_BEFORE_NOP_REGEX = '#^[ \t]+$#m';
/**
* php-parser cannot emptying a node list, it falls back to a full reprint of the parent node
* and drops blank lines between its statements; these keyword tokens let us cut just the
* emptied clause instead, e.g. the "implements" of a class that loses its last interface
*
* @var array<string, int>
*/
private const array EMPTIED_LIST_KEYWORD_TOKENS = [
Class_::class . '->implements' => \T_IMPLEMENTS,
Enum_::class . '->implements' => \T_IMPLEMENTS,
Interface_::class . '->extends' => \T_EXTENDS,
];
public function __construct(
private readonly ExprAnalyzer $exprAnalyzer,
private readonly PrivatesAccessor $privatesAccessor,
) {
parent::__construct();
}
/**
* @param Node[] $stmts
* @param Node[] $origStmts
* @param mixed[] $origTokens
*/
public function printFormatPreserving(array $stmts, array $origStmts, array $origTokens): string
{
$newStmts = $this->unwrapFileNode($stmts);
$origStmts = $this->unwrapFileNode($origStmts);
$content = parent::printFormatPreserving($newStmts, $origStmts, $origTokens);
// add new line in case of added stmts
if (count($newStmts) !== count($origStmts) && ! str_ends_with($content, "\n")) {
$content .= $this->nl;
}
return $content;
}
/**
* @param Node|Node[]|null $node
*/
public function print(Node|array|null $node): string
{
$node ??= [];
if (! is_array($node)) {
$node = [$node];
}
$node = $this->unwrapFileNode($node);
return $this->prettyPrint($node);
}
/**
* @param Node[] $stmts
*/
public function prettyPrintFile(array $stmts): string
{
// to keep indexes from 0
$stmts = array_values($stmts);
return parent::prettyPrintFile($stmts) . PHP_EOL;
}
/**
* Use for standalone InterpolatedStringPart printing, that is not support by php-parser natively.
* Used e.g. in \Rector\PhpParser\Comparing\NodeComparator::printWithoutComments
*/
protected function pInterpolatedStringPart(InterpolatedStringPart $interpolatedStringPart): string
{
return $interpolatedStringPart->value;
}
protected function p(
Node $node,
int $precedence = self::MAX_PRECEDENCE,
int $lhsPrecedence = self::MAX_PRECEDENCE,
bool $parentFormatPreserved = false
): string {
$this->wrapBinaryOpWithBrackets($node);
$content = parent::p($node, $precedence, $lhsPrecedence, $parentFormatPreserved);
// remove once its fixed in php-parser, https://github.com/nikic/PHP-Parser/pull/1126
if ($node instanceof CallLike) {
$this->cleanVariadicPlaceHolderTrailingComma($node);
}
if ($node->getAttribute(AttributeKey::WRAPPED_IN_PARENTHESES)) {
return '(' . $content . ')';
}
return $content;
}
protected function pStmt_FileNode(FileNode $fileNode): string
{
return $this->pStmts($fileNode->stmts);
}
protected function pExpr_ArrowFunction(ArrowFunction $arrowFunction, int $precedence, int $lhsPrecedence): string
{
if (! $arrowFunction->hasAttribute(AttributeKey::COMMENTS)) {
return parent::pExpr_ArrowFunction($arrowFunction, $precedence, $lhsPrecedence);
}
$expr = $arrowFunction->expr;
/** @var Comment[] $comments */
$comments = $expr->getAttribute(AttributeKey::COMMENTS) ?? [];
if ($comments === []) {
return parent::pExpr_ArrowFunction($arrowFunction, $precedence, $lhsPrecedence);
}
$isMaxPrecedence = $precedence === self::MAX_PRECEDENCE;
$isNewLineAndIndent = $arrowFunction->getAttribute(AttributeKey::IS_ARG_VALUE) === true;
$indent = $this->resolveIndentSpaces($isMaxPrecedence);
$text = $isMaxPrecedence ? '' : "\n" . $indent;
if ($isNewLineAndIndent) {
$indent = $this->resolveIndentSpaces();
$text = "\n" . $indent;
}
foreach ($comments as $key => $comment) {
$commentText = $key > 0 ? $indent . $comment->getText() : $comment->getText();
$text .= $commentText . "\n";
}
return $text . $indent . parent::pExpr_ArrowFunction($arrowFunction, $precedence, $lhsPrecedence);
}
/**
* This allows to use both spaces and tabs vs. original space-only
*/
protected function setIndentLevel(int $level): void
{
$level = max($level, 0);
$this->indentLevel = $level;
$this->nl = "\n" . str_repeat($this->getIndentCharacter(), $level);
}
/**
* This allows to use both spaces and tabs vs. original space-only
*/
protected function indent(): void
{
$indentSize = SimpleParameterProvider::provideIntParameter(Option::INDENT_SIZE);
$this->indentLevel += $indentSize;
$this->nl .= str_repeat($this->getIndentCharacter(), $indentSize);
}
/**
* This allows to use both spaces and tabs vs. original space-only
*/
protected function outdent(): void
{
if ($this->getIndentCharacter() === ' ') {
$indentSize = SimpleParameterProvider::provideIntParameter(Option::INDENT_SIZE);
assert($this->indentLevel >= $indentSize);
$this->indentLevel -= $indentSize;
} else {
// - 1 tab
assert($this->indentLevel >= 1);
--$this->indentLevel;
}
$this->nl = "\n" . str_repeat($this->getIndentCharacter(), $this->indentLevel);
}
/**
* @param mixed[] $nodes
* @param mixed[] $origNodes
*/
protected function pArray(
array $nodes,
array $origNodes,
int &$pos,
int $indentAdjustment,
string $parentNodeClass,
string $subNodeName,
?int $fixup
): ?string {
$startPos = $pos;
$content = parent::pArray($nodes, $origNodes, $pos, $indentAdjustment, $parentNodeClass, $subNodeName, $fixup);
if ($content === null) {
$cutToPos = $this->resolveEmptiedNodeListEndPos($nodes, $origNodes, $startPos, $parentNodeClass, $subNodeName);
if ($cutToPos === null) {
// restore the position possibly advanced by the parent before falling back
$pos = $startPos;
return null;
}
// drop the whole clause: whitespace + keyword + type list
$pos = $cutToPos;
return '';
}
if (! $this->containsNop($nodes)) {
return $content;
}
return Strings::replace($content, self::EXTRA_SPACE_BEFORE_NOP_REGEX);
}
/**
* php-parser bails on emptying a node list, which forces the parent node to be fully reprinted
* and loses blank lines between statements; when the whole list is removed we can instead cut
* just the emptied clause (keyword + types) and keep the rest format-preserved
*
* Returns the token position right after the removed clause, or null when not handled.
*
* @param mixed[] $nodes
* @param array<int, mixed> $origNodes
*/
private function resolveEmptiedNodeListEndPos(
array $nodes,
array $origNodes,
int $startPos,
string $parentNodeClass,
string $subNodeName
): ?int {
// only the "whole list removed" case is handled here
if ($nodes !== [] || $origNodes === []) {
return null;
}
if (! $this->origTokens instanceof TokenStream) {
return null;
}
$keywordToken = self::EMPTIED_LIST_KEYWORD_TOKENS[$parentNodeClass . '->' . $subNodeName] ?? null;
if ($keywordToken === null) {
return null;
}
$firstOrigNode = $origNodes[0];
$lastOrigNode = $origNodes[count($origNodes) - 1];
if (! $firstOrigNode instanceof Node || ! $lastOrigNode instanceof Node) {
return null;
}
$firstStartPos = $firstOrigNode->getStartTokenPos();
$lastEndPos = $lastOrigNode->getEndTokenPos();
if ($firstStartPos < 0 || $lastEndPos < 0) {
return null;
}
// the keyword must sit between the previous sub-node and the removed list
if (! $this->origTokens->haveTokenInRange($startPos, $firstStartPos, $keywordToken)) {
return null;
}
// bail on php tags in the removed range to avoid dropping them
if ($this->origTokens->haveTagInRange($startPos, $lastEndPos + 1)) {
return null;
}
return $lastEndPos + 1;
}
/**
* Do not add "()" on Expressions
* @see https://github.com/rectorphp/rector/pull/401#discussion_r181487199
*/
protected function pExpr_Yield(Yield_ $yield, int $precedence, int $lhsPrecedence): string
{
if (! $yield->value instanceof Expr) {
return 'yield';
}
// brackets are needed only in case of assign, @see https://www.php.net/manual/en/language.generators.syntax.php
$shouldAddBrackets = (bool) $yield->getAttribute(AttributeKey::IS_ASSIGNED_TO);
return sprintf(
'%syield %s%s%s',
$shouldAddBrackets ? '(' : '',
$yield->key instanceof Expr ? $this->p($yield->key) . ' => ' : '',
$this->p($yield->value),
$shouldAddBrackets ? ')' : ''
);
}
/**
* Print new lined array items when newlined_array_print is set to true
*/
protected function pExpr_Array(Array_ $array): string
{
if ($array->getAttribute(AttributeKey::NEWLINED_ARRAY_PRINT) === true) {
$printedArray = '[';
$printedArray .= $this->pCommaSeparatedMultiline($array->items, true);
return $printedArray . ($this->nl . ']');
}
return parent::pExpr_Array($array);
}
protected function pExpr_BinaryOp_Pipe(Pipe $node, int $precedence, int $lhsPrecedence): string
{
return $this->pInfixOp(
Pipe::class,
$node->left,
"\n" . $this->resolveIndentSpaces() . '|> ',
$node->right,
$precedence,
$lhsPrecedence
);
}
/**
* Fixes escaping of regular patterns
*/
protected function pScalar_String(String_ $string): string
{
if ($string->getAttribute(AttributeKey::DOC_INDENTATION) === '__REMOVED__') {
$content = parent::pScalar_String($string);
return $this->cleanStartIndentationOnHeredocNowDoc($content);
}
$isRegularPattern = (bool) $string->getAttribute(AttributeKey::IS_REGULAR_PATTERN, false);
if (! $isRegularPattern) {
return parent::pScalar_String($string);
}
$kind = $string->getAttribute(AttributeKey::KIND, String_::KIND_SINGLE_QUOTED);
if ($kind === String_::KIND_DOUBLE_QUOTED) {
return '"' . $string->value . '"';
}
if ($kind === String_::KIND_SINGLE_QUOTED) {
return "'" . $string->value . "'";
}
return parent::pScalar_String($string);
}
/**
* It remove all spaces extra to parent
*/
protected function pStmt_Declare(Declare_ $declare): string
{
$declareString = parent::pStmt_Declare($declare);
return Strings::replace($declareString, '#\s+#');
}
protected function pExpr_Ternary(Ternary $ternary, int $precedence, int $lhsPrecedence): string
{
$kind = $ternary->getAttribute(AttributeKey::KIND);
if ($kind === AttributeKey::WRAPPED_IN_PARENTHESES) {
$pExprTernary = parent::pExpr_Ternary($ternary, $precedence, $lhsPrecedence);
return '(' . $pExprTernary . ')';
}
return parent::pExpr_Ternary($ternary, $precedence, $lhsPrecedence);
}
/**
* Used in rector-downgrade-php
*/
protected function pScalar_InterpolatedString(InterpolatedString $interpolatedString): string
{
$content = parent::pScalar_InterpolatedString($interpolatedString);
if ($interpolatedString->getAttribute(AttributeKey::DOC_INDENTATION) === '__REMOVED__') {
return $this->cleanStartIndentationOnHeredocNowDoc($content);
}
return $content;
}
protected function pExpr_MethodCall(MethodCall $methodCall): string
{
if (! $methodCall->var instanceof CallLike) {
return parent::pExpr_MethodCall($methodCall);
}
$globalFlag = SimpleParameterProvider::provideBoolParameter(Option::NEW_LINE_ON_FLUENT_CALL);
$perNodeFlag = (bool) $methodCall->getAttribute(AttributeKey::NEWLINE_ON_FLUENT_CALL, false);
if ($globalFlag === false && $perNodeFlag === false) {
return parent::pExpr_MethodCall($methodCall);
}
foreach ($methodCall->args as $arg) {
if (! $arg instanceof Arg) {
continue;
}
$arg->value->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
return $this->pDereferenceLhs($methodCall->var) . "\n"
. $this->resolveIndentSpaces() . '->'
. $this->pObjectProperty($methodCall->name)
. '(' . $this->pMaybeMultiline($methodCall->args) . ')';
}
protected function pInfixOp(
string $class,
Node $leftNode,
string $operatorString,
Node $rightNode,
int $precedence,
int $lhsPrecedence
): string {
$this->wrapAssign($leftNode, $rightNode);
return parent::pInfixOp($class, $leftNode, $operatorString, $rightNode, $precedence, $lhsPrecedence);
}
protected function pExpr_Instanceof(Instanceof_ $instanceof, int $precedence, int $lhsPrecedence): string
{
$this->wrapAssign($instanceof->expr, $instanceof->class);
return parent::pExpr_Instanceof($instanceof, $precedence, $lhsPrecedence);
}
/**
* @todo remove once https://github.com/nikic/PHP-Parser/pull/1125 is merged and released
*/
private function cleanVariadicPlaceHolderTrailingComma(CallLike $callLike): void
{
$originalNode = $callLike->getAttribute(AttributeKey::ORIGINAL_NODE);
if (! $originalNode instanceof CallLike) {
return;
}
if ($originalNode->isFirstClassCallable()) {
return;
}
if (! $callLike->isFirstClassCallable()) {
return;
}
if (! $this->origTokens instanceof TokenStream) {
return;
}
/** @var Token[] $tokens */
$tokens = $this->privatesAccessor->getPrivateProperty($this->origTokens, 'tokens');
$iteration = 1;
while (isset($tokens[$callLike->getEndTokenPos() - $iteration])) {
$text = trim((string) $tokens[$callLike->getEndTokenPos() - $iteration]->text);
if (in_array($text, [')', ''], true)) {
++$iteration;
continue;
}
if ($text === ',') {
$tokens[$callLike->getEndTokenPos() - $iteration]->text = '';
}
break;
}
}
private function wrapBinaryOpWithBrackets(Node $node): void
{
if ($this->exprAnalyzer->isExprWithExprPropertyWrappable($node)) {
$node->expr->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
if (! $node instanceof BinaryOp) {
return;
}
if ($node->getAttribute(AttributeKey::ORIGINAL_NODE) instanceof Node) {
return;
}
if ($node->left instanceof Assign
&& $this->origTokens instanceof TokenStream
&& ! $this->origTokens->haveParens($node->left->getStartTokenPos(), $node->left->getEndTokenPos())) {
$node->left->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
if ($node->right instanceof Assign && $this->origTokens instanceof TokenStream) {
$node->right->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
// boolean operators (&&, ||) bind tighter than the logical ones (and, or); when
// LogicalToBooleanRector swaps them, operands with lower precedence must be reprinted
// so the pretty-printer re-adds the parentheses that keep the original semantics
if ($node instanceof BooleanAnd || $node instanceof BooleanOr) {
$this->reprintLowerPrecedenceOperand($node->left);
$this->reprintLowerPrecedenceOperand($node->right);
}
if ($node->left instanceof BinaryOp &&
$node->left->getAttribute(AttributeKey::ORIGINAL_NODE) instanceof Node) {
$node->left->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
if ($node->right instanceof BinaryOp &&
$node->right->getAttribute(AttributeKey::ORIGINAL_NODE) instanceof Node) {
$node->right->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
}
/**
* @see https://github.com/rectorphp/rector/issues/9800
*/
private function reprintLowerPrecedenceOperand(Node $node): void
{
if (! $node instanceof AssignRef
&& ! $node instanceof AssignOp
&& ! $node instanceof Ternary
&& ! $node instanceof Print_
&& ! $node instanceof Yield_
&& ! $node instanceof YieldFrom) {
return;
}
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
// the format-preserving printer keeps yield's precedence parentheses only for the
// "yield from" and empty "yield" forms; "yield <value>" needs them added explicitly
if ($node instanceof Yield_ && $node->value instanceof Expr) {
$node->setAttribute(AttributeKey::WRAPPED_IN_PARENTHESES, true);
}
}
/**
* ensure left side is assign and right side is just created
*
* @see https://github.com/rectorphp/rector-src/pull/6668
* @see https://github.com/rectorphp/rector/issues/8980
* @see https://github.com/rectorphp/rector-src/pull/6653
*/
private function wrapAssign(Node $leftNode, Node $rightNode): void
{
if ($leftNode instanceof Assign && $leftNode->getStartTokenPos() > 0 && $rightNode->getStartTokenPos() < 0) {
$leftNode->setAttribute(AttributeKey::WRAPPED_IN_PARENTHESES, true);
}
}
private function cleanStartIndentationOnHeredocNowDoc(string $content): string
{
$lines = NewLineSplitter::split($content);
$trimmedLines = array_map(ltrim(...), $lines);
return implode("\n", $trimmedLines);
}
private function resolveIndentSpaces(bool $onlyLevel = false): string
{
$indentSize = SimpleParameterProvider::provideIntParameter(Option::INDENT_SIZE);
if ($onlyLevel) {
return str_repeat($this->getIndentCharacter(), $this->indentLevel);
}
return str_repeat($this->getIndentCharacter(), $this->indentLevel) .
str_repeat($this->getIndentCharacter(), $indentSize);
}
/**
* Must be a method to be able to react to changed parameter in tests
*/
private function getIndentCharacter(): string
{
return SimpleParameterProvider::provideStringParameter(Option::INDENT_CHAR, ' ');
}
/**
* @param Node[] $stmts
* @return Node[]|mixed[]
*/
private function unwrapFileNode(array $stmts): array
{
if (count($stmts) === 1 && $stmts[0] instanceof FileNode) {
return array_values($stmts[0]->stmts);
}
return $stmts;
}
/**
* @param array<Node|null> $nodes Null in case of array destructuring
*/
private function containsNop(array $nodes): bool
{
$hasNop = false;
foreach ($nodes as $node) {
// early false when visited Node is InlineHTML
if ($node instanceof InlineHTML) {
return false;
}
// use flag to avoid next is InlineHTML that returns early
if ($node instanceof Nop) {
$hasNop = true;
}
}
return $hasNop;
}
}