diff options
author | Bruce Wells <brucekwells@gmail.com> | 2019-08-16 17:27:44 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-16 17:27:44 +0300 |
commit | ce5001573292f864471acf006b69186e2a2ba8be (patch) | |
tree | c8ea5a493e4fb91ee01b8e4221f2782e8027a88f /src | |
parent | 36b252b7c91fada20489be9ee60f173b49b823cb (diff) |
Subtraction fix (#46)v0.8.0
* Updated unit tests
* Fixed docs
* Better unary minus support
Diffstat (limited to 'src')
-rw-r--r-- | src/NXP/Classes/Lexer.php | 20 |
1 files changed, 18 insertions, 2 deletions
diff --git a/src/NXP/Classes/Lexer.php b/src/NXP/Classes/Lexer.php index 898d8c1..73c25ac 100644 --- a/src/NXP/Classes/Lexer.php +++ b/src/NXP/Classes/Lexer.php @@ -15,11 +15,12 @@ use NXP\Classes\Token\InterfaceOperator; use NXP\Classes\Token\TokenComma; use NXP\Classes\Token\TokenFunction; use NXP\Classes\Token\TokenLeftBracket; +use NXP\Classes\Token\TokenMinus; use NXP\Classes\Token\TokenNumber; use NXP\Classes\Token\TokenRightBracket; +use NXP\Classes\Token\TokenStringDoubleQuoted; use NXP\Classes\Token\TokenStringSingleQuoted; use NXP\Classes\Token\TokenVariable; -use NXP\Classes\Token\TokenStringDoubleQuoted; use NXP\Exception\IncorrectBracketsException; use NXP\Exception\IncorrectExpressionException; @@ -66,6 +67,7 @@ class Lexer { $output = []; $stack = []; + $lastToken = null; foreach ($tokensStream as $token) { if ($token instanceof TokenStringDoubleQuoted) { @@ -73,7 +75,20 @@ class Lexer } elseif ($token instanceof TokenStringSingleQuoted) { $output[] = $token; } elseif ($token instanceof TokenNumber) { - $output[] = $token; + // if the number starts with a minus sign, it could be a negative number, or it could be an operator grabbed by the greedy regex + // if previous token is an operator, then it negative, otherwise remove the minus sign and put a negative operator on the stack + if ($lastToken !== null) { + $value = (int)$token->getValue(); + if ($value < 0 && ! ($lastToken instanceof AbstractOperator)) { + $token = new TokenNumber(abs($value)); + $output[] = $token; + $output[] = new TokenMinus('-'); + } else { + $output[] = $token; + } + } else { + $output[] = $token; + } } elseif ($token instanceof TokenVariable) { $output[] = $token; } elseif ($token instanceof TokenFunction) { @@ -118,6 +133,7 @@ class Lexer $output[] = array_pop($stack); } } + $lastToken = $token; } while (!empty($stack)) { $token = array_pop($stack); |