diff options
author | Bruce Wells <bruce.wells@simparel.com> | 2019-08-16 21:02:31 +0300 |
---|---|---|
committer | Bruce Wells <bruce.wells@simparel.com> | 2019-08-16 21:02:31 +0300 |
commit | 8b5c7049907b0d2c37f98205b0fcfbdcf8374227 (patch) | |
tree | c8ea5a493e4fb91ee01b8e4221f2782e8027a88f /src/NXP | |
parent | 2bc89df821e2b98577a1b8daa1fd7349b18dcf92 (diff) | |
parent | a4849cbcc5402f3dd00965abe44df3239341bae8 (diff) |
Merge branch 'master' of https://github.com/phpfui/MathExecutor
Diffstat (limited to 'src/NXP')
-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); |