From cffcd87c062bff8edd65e75965d1f1a1fea69848 Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Fri, 3 Jul 2026 16:51:04 +1000 Subject: [PATCH] some progress --- src/New/BytecodeValue.c | 53 +++++++++++++++++++++++++++++++++++++++- src/Program/preprocess.c | 5 ++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/New/BytecodeValue.c b/src/New/BytecodeValue.c index fa555c8..f3cb70e 100644 --- a/src/New/BytecodeValue.c +++ b/src/New/BytecodeValue.c @@ -1,4 +1,55 @@ #include "../../include/ground.h" +#include + +static inline GroundBytecodeFunction doFunction(GroundFunction* function) { + GroundBytecodeFunction bf = { + .args = { + .count = function->args.count, + .capacity = function->args.count, + .at = malloc(sizeof(GroundFunctionArg) * function->args.count), + }, + .closure = NULL, + .isNativeFunction = function->isNativeFunction + }; + + if (bf.args.at == NULL) { + Ground.Log.Error("malloc failed in Ground.New.BytecodeValue -> doFunction"); + Ground.Flags.error = true; + return bf; + } + + if (function->isNativeFunction) { + bf.program.native = function->program.native; + return bf; + } + + bf.program.ground = malloc(sizeof(GroundBytecodeProgram)); + if (bf.program.ground == NULL) { + Ground.Log.Error("malloc failed in Ground.New.BytecodeValue -> doFunction"); + Ground.Flags.error = true; + return bf; + } + + // Create a state with function paramaters as first things inside state + GroundState state = {NULL, NULL, NULL, 0}; + for (GroundSize i = 0; i < bf.args.count; i++) { + GroundVariable* var = malloc(sizeof(GroundVariable)); + if (var == NULL) { + Ground.Log.Error("malloc failed in Ground.New.BytecodeValue -> doFunction"); + Ground.Flags.error = true; + return bf; + } + snprintf(var->name, 2047, "%s", function->args.at[i].as.id->string); + HASH_ADD_STR(state.variables, name, var); + } + + // Now convert the program to bytecode + GroundBytecode bytecode = Ground.New.Bytecode(function->program.ground, &state); + *bf.program.ground = bytecode.program; + free(bytecode.heap.heap); + + return bf; +} GroundBytecodeValue _GroundNewBytecodeValue(GroundValue value) { @@ -29,7 +80,7 @@ GroundBytecodeValue _GroundNewBytecodeValue(GroundValue value) { break; } case GroundType_Function: { - // TODO - convert to bytecode function + bv.as.Function = doFunction(&value.as.Function); break; } case GroundType_List: { diff --git a/src/Program/preprocess.c b/src/Program/preprocess.c index ca2e4e0..ede9221 100644 --- a/src/Program/preprocess.c +++ b/src/Program/preprocess.c @@ -106,6 +106,11 @@ GroundProgram _GroundProgramPreprocess(GroundProgram* program, GroundState* stat HASH_ADD_STR(state->variables, name, var); + // Add instruction to attach closure to function + GroundInstruction inst = Ground.New.Instruction(GroundInstruction_FUN); + Ground.Instruction.append(&inst, Ground.New.Arg.FunctionRef(sig->args.at[0].as.ref)); + Ground.Program.append(&newProgram, inst); + break; } case GroundInstruction_STRUCT: {