mirror of
https://github.com/iritmaximus/compilers.git
synced 2026-10-12 19:13:35 +03:00
Implement equals
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user