Skip to content

Commit

Permalink
Throw a ParseException if the binary token tree is improperly formatted
Browse files Browse the repository at this point in the history
  • Loading branch information
Muqsit committed Sep 24, 2022
1 parent 6431eca commit 79a5683
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/muqsit/arithmexp/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use function array_splice;
use function count;
use function is_array;
use function substr;

final class Parser{

Expand Down Expand Up @@ -59,7 +60,7 @@ public function parse(string $expression) : Expression{
$tokens = $this->scanner->scan($expression);
$this->deparenthesizeTokens($tokens);
$this->transformUnaryOperatorTokens($tokens);
$this->groupBinaryOperations($tokens);
$this->groupBinaryOperations($expression, $tokens);
$this->convertTokenTreeToPostfixTokenTree($tokens);
return new Expression(
$this->binary_operator_registry,
Expand Down Expand Up @@ -142,9 +143,10 @@ private function transformUnaryOperatorTokens(array &$tokens) : void{
* low-complexity processing, converting [TOK, BOP, TOK, BOP, TOK] to
* [[[TOK, BOP, TOK], BOP, TOK]].
*
* @param string $expression
* @param Token[]|Token[][] $tokens
*/
private function groupBinaryOperations(array &$tokens) : void{
private function groupBinaryOperations(string $expression, array &$tokens) : void{
$stack = [&$tokens];
while(($index = array_key_last($stack)) !== null){
$entry = &$stack[$index];
Expand Down Expand Up @@ -181,6 +183,9 @@ private function groupBinaryOperations(array &$tokens) : void{
/** @var Token|Token[]|Token[][] $tokens */
if($tokens instanceof Token){
$tokens = [$tokens];
}elseif(count($tokens) !== 3 || !($tokens[1] instanceof BinaryOperatorToken)){
$invalid = $tokens[1];
throw new ParseException("Unexpected {$invalid->getType()->getName()} token encountered at \"" . substr($expression, $invalid->getStartPos(), $invalid->getEndPos() - $invalid->getStartPos()) . "\" ({$invalid->getStartPos()}:{$invalid->getEndPos()}) in \"{$expression}\"");
}
}

Expand Down
2 changes: 1 addition & 1 deletion virion.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: arithmexp
antigen: muqsit\arithmexp
api: 4.9.0
version: 0.0.4
version: 0.0.5
author: Muqsit

0 comments on commit 79a5683

Please sign in to comment.