Implement equals

This commit is contained in:
Aaro Koivukangas
2026-02-28 15:06:56 +02:00
parent aa7d5d76ec
commit 77d6cc203c
2 changed files with 50 additions and 0 deletions
+16
View File
@@ -145,6 +145,21 @@ class Parser(tokens: List[Token]):
return Function(fnName, args)
def parseEquals(parsedEqualsLeft: Option[Expression], initialDepth: Int = 0): Expression =
var depth = initialDepth
val left = parsedEqualsLeft.getOrElse(parseFactor())
consume(Some("=")).get
var right = BinaryOperator(left, "=", parseExpression())
while
peek().value == "="
do
consume(Some("=")).get
right = BinaryOperator(left, "=", right)
return right
def parseExpression(initialDepth: Int = 0): Expression =
var depth = initialDepth
var left = parseFactor()
@@ -152,6 +167,7 @@ class Parser(tokens: List[Token]):
// If identifier is followed by ( => it is a function call (or syntax error :D)
left = left match {
case left: Identifier if peek().value == "(" => parseFunction(Some(left.name))
case left if peek().value == "=" => parseEquals(Some(left))
case _ => left
}
+34
View File
@@ -498,4 +498,38 @@ class ParserTests extends munit.FunSuite {
assertEquals(result, expected)
}
test("should parse simple assignment") {
val p = testParser("a = b")
val result = p.parseExpression()
val expected = BinaryOperator(Identifier("a"), "=", Identifier("b"))
assertEquals(result, expected)
}
test("should parse simple triple assignment right-associatively") {
val p = testParser("a = b = c")
val result = p.parseExpression()
val expected = BinaryOperator(
Identifier("a"),
"=",
BinaryOperator(Identifier("b"), "=", Identifier("c"))
)
assertEquals(result, expected)
}
test("should parse triple assignment with expressions right-associatively") {
val p = testParser("a = b = 1+print_bool(not true)")
val result = p.parseExpression()
val expected = BinaryOperator(
Identifier("a"),
"=",
BinaryOperator(
Identifier("b"),
"=",
BinaryOperator(Literal(1), "+", Function("print_bool", List(UnaryOperator("not", Identifier("true")))))
)
)
assertEquals(result, expected)
}
}