From d21a835072674939527ee327cb34049c072d7e75 Mon Sep 17 00:00:00 2001 From: mryouse Date: Sat, 27 May 2023 01:23:03 +0000 Subject: division --- chunk.d | 1 + compiler.d | 16 ++++++++++++++++ vm.d | 7 +++++++ 3 files changed, 24 insertions(+) diff --git a/chunk.d b/chunk.d index 02d2a69..6e572aa 100644 --- a/chunk.d +++ b/chunk.d @@ -188,6 +188,7 @@ enum OpCode { OP_POP_SCOPE, OP_SUBTRACT, OP_MULTIPLY, + OP_DIVIDE, OP_NIL, OP_JUMP, diff --git a/compiler.d b/compiler.d index f94aad3..a9d3c3d 100644 --- a/compiler.d +++ b/compiler.d @@ -255,6 +255,19 @@ class Compiler { } } + void compileDivide(Form[] args) { + if (args.length != 2) { + this.error(format("'/': expected [2] arguments, received %d", args.length), -1); + this.advance(); + return; + } + ValueType vt = this.resolve(args[0], ValueType.NUMBER); + this.func.chunk.writeOp(OpCode.OP_TYPE_CHECK_NUMBER, args[0].line); + vt = this.resolve(args[1], ValueType.NUMBER); + this.func.chunk.writeOp(OpCode.OP_TYPE_CHECK_NUMBER, args[1].line); + this.func.chunk.writeOp(OpCode.OP_DIVIDE, args[1].line); + } + //ValueType compileLess(Form[] args, ValueType expected = ValueType.ANY) { ValueType compileLess(Form[] args, ValueType expected) { if (args.length != 2) { @@ -851,6 +864,9 @@ class Compiler { case "*": this.compileMultiply(cons.tail); break; + case "/": + this.compileDivide(cons.tail); + break; // BOOLEAN case "<": diff --git a/vm.d b/vm.d index a865a50..d4fab80 100644 --- a/vm.d +++ b/vm.d @@ -507,6 +507,13 @@ class VM { double anum = asNumber(a); this.pushA(makeNumberValue(anum * bnum)); break; + case OpCode.OP_DIVIDE: + Value b = this.popA(); + Value a = this.popA(); + double bnum = asNumber(b); + double anum = asNumber(a); + this.pushA(makeNumberValue(anum / bnum)); + break; case OpCode.OP_NOT: Value val = this.popA(); bool bval = asBoolean(val); -- cgit v1.2.3