From b701a6d151a9757429aadfac0be2174c13e79dff Mon Sep 17 00:00:00 2001 From: JothamWong <45916998+JothamWong@users.noreply.github.com> Date: Tue, 16 Apr 2024 22:38:00 +0800 Subject: [PATCH] Throw error when division by 0 --- src/tests/test.ts | 9 +++++++++ src/vm/oogavm-machine.ts | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/tests/test.ts b/src/tests/test.ts index 07283f7..a5eb3a2 100644 --- a/src/tests/test.ts +++ b/src/tests/test.ts @@ -1970,3 +1970,12 @@ for i := 0; i < len(arr); i++ { } 0; `, 0, '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n', defaultNumWords); + +// Test for division by zero +testProgram(` +func foo() int { + return 0; +} + +5 / foo(); +`, 'Division by 0 error!', '', defaultNumWords); diff --git a/src/vm/oogavm-machine.ts b/src/vm/oogavm-machine.ts index 56e6442..dd203f7 100644 --- a/src/vm/oogavm-machine.ts +++ b/src/vm/oogavm-machine.ts @@ -75,7 +75,7 @@ import { Unassigned, Undefined, } from './oogavm-heap.js'; -import { OogaError } from './oogavm-errors.js'; +import { OogaError, RuntimeError } from './oogavm-errors.js'; import { unparse } from '../utils/utils.js'; import { appendHeap, appendStack } from '../server/debug.js'; @@ -353,6 +353,9 @@ function apply_binop(sym: string, left: any, right: any) { case '*': return left * right; case '/': + if (right === 0) { + throw new RuntimeError("Division by 0 error!"); + } return left / right; default: // FIXME: Propagate error properly to the VM