feat: implement modulo operator for numbers with fmod and add test suite

Add num_mod primitive using fmod from math.h to support the % operator on number types. Register the new primitive in the numClass method table. Include a comprehensive test file covering positive, negative, and left-associative modulo cases, plus a divide-by-zero TODO comment in the existing division test.
This commit is contained in:
Bob Nystrom
2013-11-10 05:01:18 +00:00
parent 98d6bbbcc1
commit c430056f70
4 changed files with 21 additions and 2 deletions
-2
View File
@@ -584,8 +584,6 @@ typedef enum
static void expression(Compiler* compiler);
static void statement(Compiler* compiler);
static void parsePrecedence(Compiler* compiler, Precedence precedence);
static ObjFn* compileFunction(Parser* parser, Compiler* parent,
TokenType endToken);
typedef void (*ParseFn)(Compiler*);
+8
View File
@@ -1,3 +1,4 @@
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -119,6 +120,12 @@ DEF_PRIMITIVE(num_divide)
return (Value)makeNum(AS_NUM(args[0]) / AS_NUM(args[1]));
}
DEF_PRIMITIVE(num_mod)
{
if (args[1]->type != OBJ_NUM) return vm->unsupported;
return (Value)makeNum(fmod(AS_NUM(args[0]), AS_NUM(args[1])));
}
DEF_PRIMITIVE(num_lt)
{
if (args[1]->type != OBJ_NUM) return vm->unsupported;
@@ -256,6 +263,7 @@ void loadCore(VM* vm)
PRIMITIVE(vm->numClass, "+ ", num_plus);
PRIMITIVE(vm->numClass, "* ", num_multiply);
PRIMITIVE(vm->numClass, "/ ", num_divide);
PRIMITIVE(vm->numClass, "% ", num_mod);
PRIMITIVE(vm->numClass, "< ", num_lt);
PRIMITIVE(vm->numClass, "> ", num_gt);
PRIMITIVE(vm->numClass, "<= ", num_lte);