Skip to content

Commit

Permalink
Properly handle new/instanceof operand restrictions
Browse files Browse the repository at this point in the history
Fixes #912.

(cherry picked from commit 1eb6b56)
  • Loading branch information
nikic committed Aug 13, 2023
1 parent cfc54e3 commit 80a680b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
9 changes: 6 additions & 3 deletions lib/PhpParser/PrettyPrinter/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -1077,9 +1077,12 @@ protected function pCallLhs(Node $node) {
}
}

protected function pNewVariable(Node $node) {
// TODO: This is not fully accurate.
return $this->pDereferenceLhs($node);
protected function pNewVariable(Node $node): string {
if (!$this->newOperandRequiresParens($node)) {
return $this->p($node);
} else {
return '(' . $this->p($node) . ')';
}
}

/**
Expand Down
16 changes: 16 additions & 0 deletions lib/PhpParser/PrettyPrinterAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -1070,6 +1070,22 @@ protected function dereferenceLhsRequiresParens(Node $node) : bool {
|| $node instanceof Expr\ClassConstFetch);
}

/**
* Determines whether an expression used in "new" or "instanceof" requires parentheses.
*
* @param Node $node New or instanceof operand
*
* @return bool Whether parentheses are required
*/
protected function newOperandRequiresParens(Node $node): bool {
return !($node instanceof Node\Name
|| $node instanceof Expr\Variable
|| $node instanceof Expr\ArrayDimFetch
|| $node instanceof Expr\PropertyFetch
|| $node instanceof Expr\NullsafePropertyFetch
|| $node instanceof Expr\StaticPropertyFetch);
}

/**
* Print modifiers, including trailing whitespace.
*
Expand Down
8 changes: 7 additions & 1 deletion test/code/prettyPrinter/expr/newVariable.test
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ Parentheses for complex new/instanceof expressions
-----
<?php
new ('a' . 'b');
new (x);
new (foo());
new ('foo');
$x instanceof ('a' . 'b');
$x instanceof ($y++);
-----
!!php7
new ('a' . 'b')();
new (x)();
new (foo())();
new ('foo')();
$x instanceof ('a' . 'b');
$x instanceof ($y++);
$x instanceof ($y++);

0 comments on commit 80a680b

Please sign in to comment.