diff options
author | Tom Willemse | 2021-01-20 22:52:47 -0800 |
---|---|---|
committer | Tom Willemse | 2021-01-20 22:52:47 -0800 |
commit | 922a8f68637f24fc447a8d687b75a676d3b310bb (patch) | |
tree | 881eccd352db8839dee5e0ef92e82af6e0dd5554 /src/com/craftinginterpreters/lox/Parser.java | |
parent | 60b940f1f5b411053ee62d5cd5188fe62e8f9e58 (diff) | |
download | crafting-interpreters-922a8f68637f24fc447a8d687b75a676d3b310bb.tar.gz crafting-interpreters-922a8f68637f24fc447a8d687b75a676d3b310bb.zip |
Add function calling syntax
Diffstat (limited to 'src/com/craftinginterpreters/lox/Parser.java')
-rw-r--r-- | src/com/craftinginterpreters/lox/Parser.java | 40 |
1 files changed, 34 insertions, 6 deletions
diff --git a/src/com/craftinginterpreters/lox/Parser.java b/src/com/craftinginterpreters/lox/Parser.java index 7d7b27a..df3ce3f 100644 --- a/src/com/craftinginterpreters/lox/Parser.java +++ b/src/com/craftinginterpreters/lox/Parser.java @@ -84,13 +84,11 @@ class Parser { Stmt body = statement(); if (increment != null) { - body = new Stmt.Block( - Arrays.asList( - body, - new Stmt.Expression(increment))); + body = new Stmt.Block(Arrays.asList(body, new Stmt.Expression(increment))); } - if (condition == null) condition = new Expr.Literal(true); + if (condition == null) + condition = new Expr.Literal(true); body = new Stmt.While(condition, body); if (initializer != null) { @@ -255,7 +253,37 @@ class Parser { return new Expr.Unary(operator, right); } - return primary(); + return call(); + } + + private Expr finishCall(Expr callee) { + List<Expr> arguments = new ArrayList<>(); + if (!check(RIGHT_PAREN)) { + do { + if (arguments.size() >= 255) { + error(peek(), "Can't have more than 255 arguments."); + } + arguments.add(expression()); + } while (match(COMMA)); + } + + Token paren = consume(RIGHT_PAREN, "Expect ')' after arguments."); + + return new Expr.Call(callee, paren, arguments); + } + + private Expr call() { + Expr expr = primary(); + + while (true) { + if (match(LEFT_PAREN)) { + expr = finishCall(expr); + } else { + break; + } + } + + return expr; } private Expr primary() { |