1
0
Fork 0
forked from fun/fun

Refactored all OP_ functions to vm/CATEGORY/ and renamed the files.

This commit is contained in:
Johannes Findeisen 2025-09-15 23:26:42 +02:00
commit 50a91d0b6f
67 changed files with 91 additions and 92 deletions

39
src/vm/arithmetic/add.c Normal file
View file

@ -0,0 +1,39 @@
case OP_ADD: {
Value b = pop_value(vm);
Value a = pop_value(vm);
if (a.type == VAL_INT && b.type == VAL_INT) {
Value res = make_int(a.i + b.i);
free_value(a);
free_value(b);
push_value(vm, res);
} else if (a.type == VAL_STRING && b.type == VAL_STRING) {
const char *sa = a.s ? a.s : "";
const char *sb = b.s ? b.s : "";
size_t la = strlen(sa);
size_t lb = strlen(sb);
char *buf = (char*)malloc(la + lb + 1);
if (!buf) {
fprintf(stderr, "Runtime error: out of memory during string concatenation\n");
exit(1);
}
memcpy(buf, sa, la);
memcpy(buf + la, sb, lb);
buf[la + lb] = '\0';
Value res;
res.type = VAL_STRING;
res.s = buf;
free_value(a);
free_value(b);
push_value(vm, res);
} else if (a.type == VAL_ARRAY && b.type == VAL_ARRAY) {
Value res = array_concat(&a, &b);
free_value(a);
free_value(b);
push_value(vm, res);
} else {
fprintf(stderr, "Runtime type error: ADD expects both ints, both strings, or both arrays, got %s and %s\n",
value_type_name(a.type), value_type_name(b.type));
exit(1);
}
break;
}

18
src/vm/arithmetic/div.c Normal file
View file

@ -0,0 +1,18 @@
case OP_DIV: {
Value b = pop_value(vm);
Value a = pop_value(vm);
if (a.type != VAL_INT || b.type != VAL_INT) {
fprintf(stderr, "Runtime type error: DIV expects ints, got %s and %s\n",
value_type_name(a.type), value_type_name(b.type));
exit(1);
}
if (b.i == 0) {
fprintf(stderr, "Runtime error: division by zero\n");
exit(1);
}
Value res = make_int(a.i / b.i);
free_value(a);
free_value(b);
push_value(vm, res);
break;
}

14
src/vm/arithmetic/mul.c Normal file
View file

@ -0,0 +1,14 @@
case OP_MUL: {
Value b = pop_value(vm);
Value a = pop_value(vm);
if (a.type != VAL_INT || b.type != VAL_INT) {
fprintf(stderr, "Runtime type error: MUL expects ints, got %s and %s\n",
value_type_name(a.type), value_type_name(b.type));
exit(1);
}
Value res = make_int(a.i * b.i);
free_value(a);
free_value(b);
push_value(vm, res);
break;
}

14
src/vm/arithmetic/sub.c Normal file
View file

@ -0,0 +1,14 @@
case OP_SUB: {
Value b = pop_value(vm);
Value a = pop_value(vm);
if (a.type != VAL_INT || b.type != VAL_INT) {
fprintf(stderr, "Runtime type error: SUB expects ints, got %s and %s\n",
value_type_name(a.type), value_type_name(b.type));
exit(1);
}
Value res = make_int(a.i - b.i);
free_value(a);
free_value(b);
push_value(vm, res);
break;
}