Function to bytecode, fix function calling

This commit is contained in:
2026-07-04 13:11:01 +10:00
parent 6385a726cf
commit 396a6d9a1b
3 changed files with 148 additions and 21 deletions

View File

@@ -1,5 +1,20 @@
#include "../../include/ground.h"
#include <stdio.h>
#include <string.h>
static void writeProgram(FILE* f, GroundBytecodeProgram* program) {
uint64_t count = program->len;
fwrite(&count, 8, 1, f);
for (GroundSize i = 0; i < count; i++) {
uint8_t type = (uint8_t)program->at[i].type;
fwrite(&type, 1, 1, f);
uint64_t argCount = program->at[i].args.len;
fwrite(&argCount, 8, 1, f);
if (argCount > 0) {
fwrite(program->at[i].args.at, sizeof(GroundSize), argCount, f);
}
}
}
static void writeValue(FILE* f, GroundBytecodeValue* v) {
switch (v->type.type) {
@@ -35,6 +50,32 @@ static void writeValue(FILE* f, GroundBytecodeValue* v) {
fwrite(v->as.String.cstr, 1, len, f);
break;
}
case GroundType_Function: {
uint8_t tag = 5;
fwrite(&tag, 1, 1, f);
uint8_t isNative = v->as.Function.isNativeFunction ? 1 : 0;
fwrite(&isNative, 1, 1, f);
uint64_t argCount = v->as.Function.args.count;
fwrite(&argCount, 8, 1, f);
for (GroundSize i = 0; i < argCount; i++) {
char* name = v->as.Function.args.at[i].as.id != NULL
? v->as.Function.args.at[i].as.id->string : "";
uint64_t len = strlen(name);
fwrite(&len, 8, 1, f);
fwrite(name, 1, len, f);
}
if (!v->as.Function.isNativeFunction && v->as.Function.program.ground != NULL) {
writeProgram(f, v->as.Function.program.ground);
} else {
uint64_t zero = 0;
fwrite(&zero, 8, 1, f);
}
// closures are generated at runtime, not persisted
break;
}
default: {
uint8_t tag = 0xFF;
fwrite(&tag, 1, 1, f);
@@ -61,15 +102,7 @@ void _GroundBytecodeSave(GroundBytecode* bytecode, const char* path) {
writeValue(f, &bytecode->heap.heap[i]);
}
count = bytecode->program.len;
fwrite(&count, 8, 1, f);
for (GroundSize i = 0; i < count; i++) {
uint8_t type = (uint8_t)bytecode->program.at[i].type;
fwrite(&type, 1, 1, f);
uint64_t argCount = bytecode->program.at[i].args.len;
fwrite(&argCount, 8, 1, f);
fwrite(bytecode->program.at[i].args.at, 8, argCount, f);
}
writeProgram(f, &bytecode->program);
fclose(f);
}