From 4ac57fc914663e1f704dfb07cce2b269efd931e9 Mon Sep 17 00:00:00 2001 From: Vaibhav Sijaria <139199971+vaibhavsijaria@users.noreply.github.com> Date: Thu, 3 Oct 2024 23:12:21 +0530 Subject: [PATCH] Refactor interpreter to handle division by zero errors --- src/error.zig | 1 + src/interpreter.zig | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/error.zig b/src/error.zig index 09ed0ba..7aea0ed 100644 --- a/src/error.zig +++ b/src/error.zig @@ -15,6 +15,7 @@ pub const RuntimeError = error{ IncompatibleTypes, InvalidOperation, NullType, + DivisionByZero, }; pub const Error = struct { diff --git a/src/interpreter.zig b/src/interpreter.zig index 11b6955..b7694b6 100644 --- a/src/interpreter.zig +++ b/src/interpreter.zig @@ -89,7 +89,13 @@ pub const Interpreter = struct { .PLUS => obj{ .num = l + right.num }, .MINUS => obj{ .num = l - right.num }, .STAR => obj{ .num = l * right.num }, - .SLASH => obj{ .num = l / right.num }, + .SLASH => slash: { + if (right.num == 0) { + Error.printerr(expr.operator, "Division by zero"); + break :slash RuntimeErrors.DivisionByZero; + } + break :slash obj{ .num = l / right.num }; + }, .GREATER => obj{ .boolean = l > right.num }, .GREATER_EQUAL => obj{ .boolean = l >= right.num }, .LESS => obj{ .boolean = l < right.num },