Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ abstract class ExpressionParser(val opDef: OperatorsDefinition) {
if (exp.isEmpty)
throw new IllegalArgumentException("Expression must not be empty")
val nodes = getNodesAtLevel(exp)
makeTreeFromNodes(nodes.toSeq)
makeTreeFromNodes(nodes.toSeq, exp)
}

/** Recursive method to find all cells for the terms at the current parenthesized level. */
Expand All @@ -41,7 +41,7 @@ abstract class ExpressionParser(val opDef: OperatorsDefinition) {
if (ch == LexToken.RightParen.symbol) parenCount -= 1
}

if (ch != LexToken.RightParen.symbol && i == exp.length)
if (parenCount != 0)
throw new ParseError(pos, "Mismatched parenthesis", exp)
i - 1
}
Expand All @@ -56,6 +56,6 @@ abstract class ExpressionParser(val opDef: OperatorsDefinition) {
protected def pushNodesForToken(token: String, nodes: ListBuffer[ParseListItem], exp: String, tokenEndPos: Int): Unit

/** Converts a flat list to a single [[Expr]] by reducing in order of operator precedence. */
protected def makeTreeFromNodes(nodes: Seq[ParseListItem]): Expr =
new PrecedenceReducer(opDef.getOperatorPrecedence).reduce(nodes)
protected def makeTreeFromNodes(nodes: Seq[ParseListItem], source: String = ""): Expr =
new PrecedenceReducer(opDef.getOperatorPrecedence, source).reduce(nodes)
}
17 changes: 10 additions & 7 deletions scala-source/com/barrybecker4/expression/PrecedenceReducer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,37 @@ import scala.collection.mutable.ListBuffer
* Reduces a flat infix token list to a single [[Expr]] by applying operator
* precedence groups left-to-right within each level.
*/
private[expression] final class PrecedenceReducer(precedence: Array[Array[Operator]]) {
private[expression] final class PrecedenceReducer(
precedence: Array[Array[Operator]],
source: String = ""
) {

def reduce(items: Seq[ParseListItem]): Expr = {
if (items.isEmpty)
throw new ParseError(-1, "Empty expression fragment", "")
throw new ParseError(-1, "Empty expression fragment", source)
val nodes = ListBuffer.from(items)
for (ops <- precedence) reduceNodes(ops, nodes)
if (nodes.size > 1)
throw new ParseError(-1, "Expected to have only one node after reducing, but have " + nodes.size + " : " + nodes, "")
throw new ParseError(-1, "Expected to have only one node after reducing, but have " + nodes.size, source)
nodes.head match {
case PlOperand(e) => e
case PlOperator(_) => throw new ParseError(-1, "Missing operands", "")
case PlOperator(_) => throw new ParseError(-1, "Missing operands", source)
}
}

private def reduceNodes(ops: Array[Operator], nodes: ListBuffer[ParseListItem]): Unit = {
var index = 1
if (nodes.size == 2)
throw new ParseError(-1, "Missing operand : " + nodes, "")
throw new ParseError(-1, "Missing operand", source)
while (index < nodes.size) {
if (isOperatorCell(nodes(index), ops)) {
if (index + 1 >= nodes.size)
throw new ParseError(-1, "Not enough operands for operator in nodes=" + nodes, "")
throw new ParseError(-1, "Not enough operands for operator", source)
(nodes(index - 1), nodes(index), nodes(index + 1)) match {
case (PlOperand(l), PlOperator(op), PlOperand(r)) =>
splice(nodes, index - 1, 3, PlOperand(BinOp(op, l, r)))
case _ =>
throw new ParseError(-1, "Malformed operator/operand sequence: " + nodes, "")
throw new ParseError(-1, "Malformed operator/operand sequence", source)
}
}
else index += 2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,23 @@ class MathExpressionParser(opDef: OperatorsDefinition = new MathOperatorsDefinit
if (pos < exp.length) ch = exp.charAt(pos)
}
pushNodesForToken(token, nodes, exp, math.max(0, pos - 1))
rejectDanglingOperators(nodes, exp, math.max(0, pos - 1))
nodes
}

/** Catch leading/trailing operators while the character index is still known. */
private def rejectDanglingOperators(nodes: ListBuffer[ParseListItem], exp: String, lastPos: Int): Unit = {
if (nodes.isEmpty) return
nodes.head match {
case PlOperator(_) => throw new ParseError(0, "Missing operand", exp)
case _ =>
}
nodes.last match {
case PlOperator(_) => throw new ParseError(lastPos, "Missing operand", exp)
case _ =>
}
}

override protected def processSubExpression(exp: String, pos: Int,
token: String, closingParenPos: Int,
nodes: ListBuffer[ParseListItem]): String = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,13 @@ class MathExpressionParserExtendedSuite extends AnyFunSuite {
Assertions.intercept[IllegalArgumentException](parser.parse("1+"))
}

test("trailing operator points at the original text") {
val ex = Assertions.intercept[ParseError](parser.parse("1+"))
assert(ex.source === "1+")
assert(ex.offset === 1)
assert(!ex.getMessage.contains("ListBuffer"))
}

test("reject leading binary operator after nullary start would be invalid - lone star") {
Assertions.intercept[IllegalArgumentException](parser.parse("*3"))
}
Expand All @@ -183,6 +190,12 @@ class MathExpressionParserExtendedSuite extends AnyFunSuite {
Assertions.intercept[IllegalArgumentException](parser.parse("1+*2"))
}

test("malformed operator sequence still names the original expression") {
val ex = Assertions.intercept[ParseError](parser.parse("1+*2"))
assert(ex.source === "1+*2")
assert(!ex.getMessage.contains("ListBuffer"))
}

test("reject malformed decimal with adjacent dots") {
Assertions.intercept[IllegalArgumentException | NumberFormatException] {
parser.parse("1..2")
Expand All @@ -193,6 +206,12 @@ class MathExpressionParserExtendedSuite extends AnyFunSuite {
Assertions.intercept[ParseError](parser.parse("((x+1)"))
}

test("extra open paren is reported against the full expression") {
val ex = Assertions.intercept[ParseError](parser.parse("((x)"))
assert(ex.source === "((x)")
assert(ex.getMessage.contains("Mismatched"))
}

// --- parse == parse (idempotent string round-trip shape) ---

test("re-serializing complex parse does not change on second parse") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ class MathExpressionParserSuite extends AnyFunSuite {
test("parse rejects mismatched parenthesis") {
val ex = Assertions.intercept[ParseError](parser.parse("(x+1"))
assert(ex.getMessage.contains("Mismatched"))
assert(ex.source === "(x+1")
}

test("mixed exponent subtraction and multiplication") {
Expand Down
Loading