class Runner:
def init(self, evaluator):
self.evaluator = evaluator
code
def run(self, statements):
for statement in statements:
self.evaluator.execute(statement)
def main():
code
if len(sys.argv) < 3:
print("Usage: ./your_program.sh tokenize <filename>", file=sys.stderr)
exit(1)
command = sys.argv[1]
filename = sys.argv[2]
with open(filename) as file:
file_contents = file.read()
if command == "run":
try:
ast = parse(file_contents)
if Lox.had_error:
sys.exit(65)
evaluator = Evaluator()
runner = Runner(evaluator)
runner.run(ast)
except SyntaxError as e:
print(f"[line {e.line}] Error at '{e.token.lexeme}': {e.message}", file=sys.stderr)
sys.exit(65)
except LoxRuntimeError as e:
sys.exit(70)
elif command == "parse":
try:
ast = parse(file_contents)
if Lox.had_error:
sys.exit(65)
if ast:
for stmt in ast:
ast_str = ast_to_string(stmt)
print(ast_str)
else:
print('nil')
except SyntaxError as e:
print(f"[line {e.line}] Error at '{e.token.lexeme}': {e.message}", file=sys.stderr)
sys.exit(65)
elif command == "tokenize":
if file_contents:
tokens = tokenize(file_contents)
for token in tokens:
print(token)
else:
print("EOF null")
if Lox.had_error:
sys.exit(65)
elif command == "evaluate":
try:
ast = parse(file_contents)
if Lox.had_error:
sys.exit(65)
evaluator = Evaluator()
result = None
for stmt in ast:
if stmt[0] == 'expr':
result = evaluator.evaluate(stmt[1])
elif stmt[0] == 'print':
result = evaluator.evaluate(stmt[1])
print_value(result)
if result is not None:
print_value(result)
if result is None:
print("nil")
except SyntaxError as e:
print(f"[line {e.token.line}] Error at '{e.token.lexeme}': {e.message}", file=sys.stderr)
sys.exit(65)
except LoxRuntimeError as e:
print(e.message, file=sys.stderr)
print(f"[line {e.line}]", file=sys.stderr)
sys.exit(70)
else:
print(f"Unknown command: {command}", file=sys.stderr)
exit(1)
def print_value(value):
if isinstance(value, bool):
print("true" if value else "false")
elif isinstance(value, float) and value.is_integer():
print(int(value))
elif value is None:
print("nil")
else:
print(value)
if name == "main":
main()
The error you're encountering stems from a mismatch in the LoxRuntimeError class's initialization parameters. Specifically, when raising a LoxRuntimeError, the line argument is missing, leading to a TypeError. Let's delve into the root cause and provide a comprehensive solution to fix this issue.
In your Evaluator class, particularly within the check_number_operands method, you're raising a LoxRuntimeError without providing the required line argument. The LoxRuntimeError class is defined to expect both a message and a line number when instantiated.
Relevant Code Snippet:
python
class LoxRuntimeError(Exception):
def __init__(self, message, line):
super().__init__(message)
self.message = message
self.line = line
class Evaluator:
# ... other methods ...
def check_number_operands(self, left, right):
if isinstance(left, bool) or isinstance(right, bool):
raise LoxRuntimeError("Operands must be numbers.")
if not isinstance(left, (int, float)) or not isinstance(right, (int, float)):
raise LoxRuntimeError("Operands must be numbers.")
In the check_number_operands method, LoxRuntimeError is raised without the line argument, causing the TypeError.
Solution
To resolve this issue, you need to ensure that every time you raise a LoxRuntimeError, you provide both the message and the corresponding line number where the error occurred. Here's a step-by-step guide to implement this fix:
1. Modify the check_number_operands Method:
Update the check_number_operands method to accept an additional line parameter. This parameter should represent the line number where the error is detected.
python
class Evaluator:
# ... other methods ...
def check_number_operands(self, left, right, line):
if isinstance(left, bool) or isinstance(right, bool):
raise LoxRuntimeError("Operands must be numbers.", line)
if not isinstance(left, (int, float)) or not isinstance(right, (int, float)):
raise LoxRuntimeError("Operands must be numbers.", line)
2. Update Calls to check_number_operands:
Whenever check_number_operands is called, pass the appropriate line number. Typically, this line number can be extracted from the AST node representing the operation. Here's how you can adjust the evaluate method to pass the line number:
python
class Evaluator:
# ... other methods ...
def evaluate(self, expr):
if isinstance(expr, tuple):
operator = expr[0]
if operator in ('-', '!', '*', '/', '%', '+', '>', '>=', '<', '<=', '==', '!='):
# Assuming binary operators have the structure: (operator, left, right, line)
if len(expr) == 4:
_, left_expr, right_expr, line = expr
else:
# Handle cases where line number might not be present
_, left_expr, right_expr = expr
line = 0 # Default line number or handle appropriately
left = self.evaluate(left_expr)
right = self.evaluate(right_expr)
if operator in ('*', '/', '%', '-', '+'):
self.check_number_operands(left, right, line)
# Perform the operation...
# Handle other operators similarly...
# Example for multiplication
if operator == '*':
return left * right
# ... handle other operators
# ... handle other cases
3. Ensure AST Nodes Carry Line Information:
For this fix to work seamlessly, ensure that your AST (Abstract Syntax Tree) nodes include line information. When parsing expressions, include the line number in the tuple structure. For instance:
python
def parse_addition(self):
expr = self.parse_multiplication()
while self.match('PLUS', 'MINUS'):
operator = self.previous().lexeme
right = self.parse_multiplication()
line = self.previous().line # Assuming each token has a 'line' attribute
expr = (operator, expr, right, line)
return expr
4. Comprehensive Example:
Here's how you can incorporate these changes into your existing code:
python
5. Updated Error Handling in the main Function:
Ensure that when a LoxRuntimeError is caught in the main function, it properly outputs the error message along with the line number.
python
def main():
# ... existing code ...
if command == "run":
try:
ast = parse(file_contents)
if Lox.had_error:
sys.exit(65)
evaluator = Evaluator()
runner = Runner(evaluator)
runner.run(ast)
except SyntaxError as e:
print(f"[line {e.line}] Error at '{e.token.lexeme}': {e.message}", file=sys.stderr)
sys.exit(65)
except LoxRuntimeError as e:
print(f"[line {e.line}] {e.message}", file=sys.stderr)
sys.exit(70)
6. Testing the Fix:
After implementing the above changes, rerun your test case to ensure the error is resolved.
Test Input (test.lox):
lox
print "62" + "foo";
print true * (49 + 72);
Expected Output:
code
62foo
[line X] Operands must be numbers.
(Replace X with the actual line number where the error occurs.)
Conclusion
By ensuring that every LoxRuntimeError is instantiated with both a message and a line number, you align with the class's initialization requirements, thereby preventing the TypeError. This not only resolves the immediate error but also enhances the robustness of your error-handling mechanism, providing clearer and more informative error messages to users.
If you encounter further issues or have additional questions, feel free to ask!
Not yet included in a published release.
class Evaluator:
def __init__(self):
self.environment = Environment()
self.environment.define("clock", NativeFunction("clock", 0, native_clock))
def evaluate(self, expr):
if isinstance(expr, tuple):
operator = expr[0]
# Binary Operators
if operator in ('*', '/', '%', '-', '+', '>', '>=', '<', '<=', '==', '!='):
if len(expr) == 4:
_, left_expr, right_expr, line = expr
else:
_, left_expr, right_expr = expr
line = 0 # Or handle appropriately
left = self.evaluate(left_expr)
right = self.evaluate(right_expr)
# Check number operands if necessary
if operator in ('*', '/', '%', '-', '+', '>', '>=', '<', '<='):
self.check_number_operands(left, right, line)
if operator == '*':
return left * right
elif operator == '/':
return left / right
elif operator == '%':
return left % right
elif operator == '-':
return left - right
elif operator == '+':
if isinstance(left, (int, float)) and isinstance(right, (int, float)):
return left + right
elif isinstance(left, str) and isinstance(right, str):
return left + right
else:
raise LoxRuntimeError("Operands must be two numbers or two strings.", line)
elif operator == '>':
return left > right
elif operator == '>=':
return left >= right
elif operator == '<':
return left < right
elif operator == '<=':
return left <= right
elif operator == '==':
return left == right
elif operator == '!=':
return left != right
# Unary Operators
elif operator in ('-', '!'):
_, operand_expr, line = expr
operand = self.evaluate(operand_expr)
if operator == '-':
self.check_number_operand(operand, line)
return -operand
elif operator == '!':
return not self.is_truthy(operand)
# ... handle other operators and expressions
elif isinstance(expr, bool):
return expr
elif expr is None:
return None
elif isinstance(expr, (int, float, str)):
return expr
else:
raise LoxRuntimeError("Unknown expression type.", 0)
def check_number_operands(self, left, right, line):
if isinstance(left, bool) or isinstance(right, bool):
raise LoxRuntimeError("Operands must be numbers.", line)
if not isinstance(left, (int, float)) or not isinstance(right, (int, float)):
raise LoxRuntimeError("Operands must be numbers.", line)
def check_number_operand(self, operand, line):
if isinstance(operand, bool):
raise LoxRuntimeError("Operand must be a number.", line)
if not isinstance(operand, (int, float)):
raise LoxRuntimeError("Operand must be a number.", line)
# ... rest of the Evaluator class