diff --git a/lib/PhpParser/Internal/TokenStream.php b/lib/PhpParser/Internal/TokenStream.php index cdbe2bdcc9..827f363b33 100644 --- a/lib/PhpParser/Internal/TokenStream.php +++ b/lib/PhpParser/Internal/TokenStream.php @@ -220,12 +220,19 @@ public function getIndentationBefore(int $pos): int { * * @return string Code corresponding to token range, adjusted for indentation */ - public function getTokenCode(int $from, int $to, int $indent): string { + public function getTokenCode(int $from, int $to, int $indent, bool $removeTrailingComma = false): string { $tokens = $this->tokens; $result = ''; for ($pos = $from; $pos < $to; $pos++) { $token = $tokens[$pos]; $id = $token->id; + + if ($removeTrailingComma && $token->text === ',') { + $token->text = ''; + // don't try to remove trailing comma multiple times + $removeTrailingComma = false; + } + $text = $token->text; if ($id === \T_CONSTANT_ENCAPSED_STRING || $id === \T_ENCAPSED_AND_WHITESPACE) { $result .= $text; diff --git a/lib/PhpParser/PrettyPrinterAbstract.php b/lib/PhpParser/PrettyPrinterAbstract.php index 448bc84919..4d5d3825e5 100644 --- a/lib/PhpParser/PrettyPrinterAbstract.php +++ b/lib/PhpParser/PrettyPrinterAbstract.php @@ -10,6 +10,7 @@ use PhpParser\Node\Expr; use PhpParser\Node\Expr\AssignOp; use PhpParser\Node\Expr\BinaryOp; +use PhpParser\Node\Expr\CallLike; use PhpParser\Node\Expr\Cast; use PhpParser\Node\IntersectionType; use PhpParser\Node\MatchArm; @@ -765,7 +766,12 @@ protected function p( $pos = $subEndPos + 1; } - $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment); + if ($node instanceof CallLike && substr(trim($result), -3) === '...' && $node->isFirstClassCallable()) { + $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment, true); + } else { + $result .= $this->origTokens->getTokenCode($pos, $endPos + 1, $indentAdjustment); + } + return $result; } diff --git a/test/code/formatPreservation/change_args_to_variadic_placeholder.test b/test/code/formatPreservation/change_args_to_variadic_placeholder.test new file mode 100644 index 0000000000..962e251df1 --- /dev/null +++ b/test/code/formatPreservation/change_args_to_variadic_placeholder.test @@ -0,0 +1,13 @@ +Replace args with VariadicPlaceholder should remove trailing comma +----- +expr->args = [new Node\VariadicPlaceholder()]; +----- +