Skip to content

Commit

Permalink
Refactor interpreter to handle division by zero errors
Browse files Browse the repository at this point in the history
  • Loading branch information
vaibhavsijaria committed Oct 3, 2024
1 parent f359d33 commit 4ac57fc
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/error.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub const RuntimeError = error{
IncompatibleTypes,
InvalidOperation,
NullType,
DivisionByZero,
};

pub const Error = struct {
Expand Down
8 changes: 7 additions & 1 deletion src/interpreter.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down

0 comments on commit 4ac57fc

Please sign in to comment.