Skip to content

Commit

Permalink
Compile Elvis operator with Elvis operator
Browse files Browse the repository at this point in the history
  • Loading branch information
GromNaN committed Oct 21, 2023
1 parent 51cfad8 commit fb0d749
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
3 changes: 3 additions & 0 deletions src/ExpressionParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,14 @@ private function parseConditionalExpression($expr): AbstractExpression
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
$expr2 = $this->parseExpression();
if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
// Ternary operator (expr ? expr2 : expr3)
$expr3 = $this->parseExpression();
} else {
// Ternary without else (expr ? expr2)
$expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine());
}
} else {
// Ternary without then (expr ?: expr3)
$expr2 = $expr;
$expr3 = $this->parseExpression();
}
Expand Down
27 changes: 18 additions & 9 deletions src/Node/Expression/ConditionalExpression.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,23 @@ public function __construct(AbstractExpression $expr1, AbstractExpression $expr2

public function compile(Compiler $compiler): void
{
$compiler
->raw('((')
->subcompile($this->getNode('expr1'))
->raw(') ? (')
->subcompile($this->getNode('expr2'))
->raw(') : (')
->subcompile($this->getNode('expr3'))
->raw('))')
;
// Ternary with no then uses Elvis operator
if ($this->getNode('expr1') === $this->getNode('expr2')) {
$compiler
->raw('((')
->subcompile($this->getNode('expr1'))
->raw(') ?: (')
->subcompile($this->getNode('expr3'))
->raw('))');
} else {
$compiler
->raw('((')
->subcompile($this->getNode('expr1'))
->raw(') ? (')
->subcompile($this->getNode('expr2'))
->raw(') : (')
->subcompile($this->getNode('expr3'))
->raw('))');
}
}
}

0 comments on commit fb0d749

Please sign in to comment.