Skip to content

Commit

Permalink
Do not perform strength reduction x - x => 0 between numeric litera…
Browse files Browse the repository at this point in the history
…ls (address #16)

Constant folding will resolve this on its next visit by executing the operation instead of direct substitution
  • Loading branch information
Muqsit committed Nov 1, 2022
1 parent 1de0e16 commit 1ef49eb
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@

final class OperatorStrengthReductionExpressionOptimizer implements ExpressionOptimizer{

private PatternMatcher $any_non_numeric_matcher;
private PatternMatcher $binary_operation_matcher;
private PatternMatcher $unary_operation_matcher;
private PatternMatcher $multiplication_operation_matcher;
private PatternMatcher $exponentiation_operation_matcher;

public function __construct(){
$this->any_non_numeric_matcher = Pattern::not(Pattern::instanceof(NumericLiteralExpressionToken::class));
$this->binary_operation_matcher = new ArrayPatternMatcher([
AnyPatternMatcher::instance(),
AnyPatternMatcher::instance(),
Expand Down Expand Up @@ -207,7 +209,7 @@ private function processBinaryExpression(Parser $parser, Expression $expression,
default => $this->processAddition($parser, $operator_token, $left, $right)
},
"-" => match(true){
$this->tokensEqualByReturnValue($left, $right) => [new NumericLiteralExpressionToken(Util::positionContainingExpressionTokens([...$left, ...$right]), 0)],
$this->tokensEqualByReturnValue($left, $right) && $this->any_non_numeric_matcher->matches([...$left, ...$right]) => [new NumericLiteralExpressionToken(Util::positionContainingExpressionTokens([...$left, ...$right]), 0)],
$this->valueEquals($left, 0) => [
new NumericLiteralEXpressionToken(Util::positionContainingExpressionTokens($right), -1),
...$right,
Expand Down
6 changes: 6 additions & 0 deletions tests/muqsit/arithmexp/OptimizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,12 @@ public function testSubtractionOperatorStrengthReductionForEqualOperands() : voi
self::assertEquals(0, $expression->evaluate());
}

public function testSubtractionOperatorStrengthReductionForEqualOperandsYieldingNaN() : void{
$expression = $this->parser->parse("inf - inf");
self::assertInstanceOf(ConstantExpression::class, $expression);
self::assertNan($expression->evaluate());
}

public function testSubtractionOperatorStrengthReductionForEqualOperandsWithGrouping() : void{
$expression = $this->parser->parse("(x * y * z) - (x * y * z)");
self::assertInstanceOf(ConstantExpression::class, $expression);
Expand Down

0 comments on commit 1ef49eb

Please sign in to comment.