From 2e11deec467d9348e50f6497c94970ec5ae74c7a Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Wed, 21 Sep 2022 20:38:21 +0200 Subject: [PATCH] Bail out on PHP tags in removed code If dropping a node would drop PHP tags, bail out of formatting preservation. This will lose formatting, but at least produce legal code. Closes GH-884. (cherry picked from commit b0edd4c41111042d43bb45c6c657b2e0db367d9e) --- lib/PhpParser/Internal/TokenStream.php | 5 ++++ lib/PhpParser/PrettyPrinterAbstract.php | 6 +++-- test/code/formatPreservation/inlineHtml.test | 28 +++++++++++--------- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/lib/PhpParser/Internal/TokenStream.php b/lib/PhpParser/Internal/TokenStream.php index 84c0175ec5..7e0a5de0f1 100644 --- a/lib/PhpParser/Internal/TokenStream.php +++ b/lib/PhpParser/Internal/TokenStream.php @@ -206,6 +206,11 @@ public function haveBracesInRange(int $startPos, int $endPos) { || $this->haveTokenInRange($startPos, $endPos, '}'); } + public function haveTagInRange(int $startPos, int $endPos): bool { + return $this->haveTokenInRange($startPos, $endPos, \T_OPEN_TAG) + || $this->haveTokenInRange($startPos, $endPos, \T_CLOSE_TAG); + } + /** * Get indentation before token position. * diff --git a/lib/PhpParser/PrettyPrinterAbstract.php b/lib/PhpParser/PrettyPrinterAbstract.php index 82b1e35587..6ed936fedd 100644 --- a/lib/PhpParser/PrettyPrinterAbstract.php +++ b/lib/PhpParser/PrettyPrinterAbstract.php @@ -774,7 +774,8 @@ protected function pArray( } if ($skipRemovedNode) { - if ($isStmtList && $this->origTokens->haveBracesInRange($pos, $itemStartPos)) { + if ($isStmtList && ($this->origTokens->haveBracesInRange($pos, $itemStartPos) || + $this->origTokens->haveTagInRange($pos, $itemStartPos))) { // We'd remove the brace of a code block. // TODO: Preserve formatting. $this->setIndentLevel($origIndentLevel); @@ -877,7 +878,8 @@ protected function pArray( $pos, $itemStartPos, $indentAdjustment); $skipRemovedNode = true; } else { - if ($isStmtList && $this->origTokens->haveBracesInRange($pos, $itemStartPos)) { + if ($isStmtList && ($this->origTokens->haveBracesInRange($pos, $itemStartPos) || + $this->origTokens->haveTagInRange($pos, $itemStartPos))) { // We'd remove the brace of a code block. // TODO: Preserve formatting. return null; diff --git a/test/code/formatPreservation/inlineHtml.test b/test/code/formatPreservation/inlineHtml.test index ae25cc64da..0b131fed09 100644 --- a/test/code/formatPreservation/inlineHtml.test +++ b/test/code/formatPreservation/inlineHtml.test @@ -42,13 +42,14 @@ function test() { baz(); } ----- -// TODO Fix broken result +// TODO Preserve formatting $stmts[0]->stmts[1] = $stmts[0]->stmts[2]; ----- stmts[2]); ----- Bar + ?>Barstmts, 0, 1, []); ----- Barstmts, 1, 1, []); -----