diff --git a/src/parser/Parser.java b/src/parser/Parser.java index 722a3f6..2981cde 100644 --- a/src/parser/Parser.java +++ b/src/parser/Parser.java @@ -1,6 +1,7 @@ package parser; import expression.*; +import expression.Identifier; import expression.Int; import program.*; @@ -51,12 +52,25 @@ public class Parser { statement = conditional(); } catch (SyntaxException se2) { position = start; - statement = loop(); + try { + statement = loop(); + } catch (SyntaxException se3) { + position = start; + statement = call(); + } } } return statement; } + Program call() { + Identifier name = identifier(); + consume("("); + Expression argument = expression(); + consume(")"); + return new Call(name, argument); + } + Program loop() { consume("while"); consume("("); diff --git a/src/program/Call.java b/src/program/Call.java new file mode 100644 index 0000000..effb040 --- /dev/null +++ b/src/program/Call.java @@ -0,0 +1,38 @@ +package program; + +import expression.Expression; +import expression.Identifier; + +public class Call extends Program { + final Identifier name; + final Expression argument; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Call that = (Call) o; + + if (!name.equals(that.name)) return false; + return argument.equals(that.argument); + + } + + @Override + public String toString() { + return name + "(" + argument + ")"; + } + + @Override + public int hashCode() { + int result = name.hashCode(); + result = 31 * result + argument.hashCode(); + return result; + } + + public Call(Identifier name, Expression argument) { + this.name = name; + this.argument = argument; + } +} diff --git a/test/parser/ParserTest.java b/test/parser/ParserTest.java index cc219e6..a1fb186 100644 --- a/test/parser/ParserTest.java +++ b/test/parser/ParserTest.java @@ -52,6 +52,15 @@ public class ParserTest { assertEquals(loop, parser.statement()); } + final String callCode = "print(x + 36)"; + final Call call = new Call(new Identifier("print"), new Addition(new Identifier("x"), new Int(36))); + + @Test + public void testStatementCall() { + Parser parser = new Parser(callCode); + assertEquals(call, parser.statement()); + } + @Test public void testAssignment() { Parser parser = new Parser(assignmentCode); @@ -70,6 +79,12 @@ public class ParserTest { assertEquals(loop, parser.loop()); } + @Test + public void testCall() { + Parser parser = new Parser(callCode); + assertEquals(call, parser.call()); + } + final String expressionCode = "a+b - (c - 56) + -47"; final Expression expression = new Addition(new Subtraction(new Addition(new Identifier("a"), new Identifier("b")), new Subtraction(new Identifier("c"), new Int(56))), new Int(-47));