aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/craftinginterpreters/lox/Interpreter.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/com/craftinginterpreters/lox/Interpreter.java')
-rw-r--r--src/com/craftinginterpreters/lox/Interpreter.java30
1 files changed, 27 insertions, 3 deletions
diff --git a/src/com/craftinginterpreters/lox/Interpreter.java b/src/com/craftinginterpreters/lox/Interpreter.java
index f752e77..407c537 100644
--- a/src/com/craftinginterpreters/lox/Interpreter.java
+++ b/src/com/craftinginterpreters/lox/Interpreter.java
@@ -4,7 +4,23 @@ import java.util.ArrayList;
import java.util.List;
class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
- private Environment environment = new Environment();
+ final Environment globals = new Environment();
+ private Environment environment = globals;
+
+ Interpreter() {
+ globals.define("clock", new LoxCallable() {
+ @Override
+ public int arity() { return 0; }
+
+ @Override
+ public Object call(Interpreter interpreter, List<Object> arguments) {
+ return (double)System.currentTimeMillis() / 1000.0;
+ }
+
+ @Override
+ public String toString() { return "<native fn>"; }
+ });
+ }
@Override
public Object visitLiteralExpr(Expr.Literal expr) {
@@ -105,7 +121,7 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
stmt.accept(this);
}
- private void executeBlock(List<Stmt> statements, Environment environment) {
+ public void executeBlock(List<Stmt> statements, Environment environment) {
Environment previous = this.environment;
try {
@@ -132,6 +148,13 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
}
@Override
+ public Void visitFunctionStmt(Stmt.Function stmt) {
+ LoxFunction function = new LoxFunction(stmt);
+ environment.define(stmt.name.lexeme, function);
+ return null;
+ }
+
+ @Override
public Void visitIfStmt(Stmt.If stmt) {
if (isTruthy(evaluate(stmt.condition))) {
execute(stmt.thenBranch);
@@ -238,7 +261,8 @@ class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
LoxCallable function = (LoxCallable) callee;
if (arguments.size() != function.arity()) {
- throw new RuntimeError(expr.paren, "Expected " + function.arity() + " arguments but got " + arguments.size() + ".");
+ throw new RuntimeError(expr.paren,
+ "Expected " + function.arity() + " arguments but got " + arguments.size() + ".");
}
return function.call(this, arguments);