From ac2621e43182fe1bf07dd40ea797d5f28882f1c9 Mon Sep 17 00:00:00 2001 From: Sebastian Hugentobler Date: Tue, 11 Feb 2025 10:16:46 +0100 Subject: [PATCH] document java interpretere --- .../ch/vanwa/lox_interpreter/Interpreter.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/java/lox-interpreter/src/main/java/ch/vanwa/lox_interpreter/Interpreter.java b/java/lox-interpreter/src/main/java/ch/vanwa/lox_interpreter/Interpreter.java index 26be683..93d4a77 100644 --- a/java/lox-interpreter/src/main/java/ch/vanwa/lox_interpreter/Interpreter.java +++ b/java/lox-interpreter/src/main/java/ch/vanwa/lox_interpreter/Interpreter.java @@ -1,5 +1,8 @@ package ch.vanwa.lox_interpreter; +/** + * Evaluate Lox expressions. + */ class Interpreter implements Expr.Visitor { void interpret(Expr expression) { try { @@ -87,12 +90,18 @@ class Interpreter implements Expr.Visitor { return null; } + /** + * Throw a runtime error if the operand is not an instance of Double. + */ private void checkNumberOperand(Token operator, Object operand) { if (operand instanceof Double) return; throw new RuntimeError(operator, "Operand must be a number."); } + /** + * Throw a runtime error if left and right are not both instances of Double. + */ private void checkNumberOperands(Token operator, Object left, Object right) { if (left instanceof Double && right instanceof Double) @@ -101,6 +110,9 @@ class Interpreter implements Expr.Visitor { throw new RuntimeError(operator, "Operands must be numbers."); } + /** + * Return true if the object is a boolean with value true, false otherwise. + */ private boolean isTruthy(Object object) { if (object == null) return false; @@ -109,6 +121,10 @@ class Interpreter implements Expr.Visitor { return true; } + /** + * Return true if object a and b are not null and a equals be, otherwise return + * false. + */ private boolean isEqual(Object a, Object b) { if (a == null && b == null) return true; @@ -118,6 +134,12 @@ class Interpreter implements Expr.Visitor { return a.equals(b); } + /** + * Convert an object to a string. + * + * If the object is null, return "nil", if it is a Double properly print it as a + * decimal, otherwise just call toString. + */ private String stringify(Object object) { if (object == null) { return "nil";