mvm-tests/main.c

88 lines
2.5 KiB
C

#include "stdio.h"
#include "string.h"
#include "termios.h"
#include "microvium.h"
unsigned char main_mvm_bc[] = {
0x06, 0x1c, 0x06, 0x00, 0x7c, 0x00, 0xc1, 0xda, 0x03, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x20, 0x00, 0x24, 0x00, 0x24, 0x00, 0x2a, 0x00, 0x2c, 0x00,
0x68, 0x00, 0x72, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x51, 0x00,
0x71, 0x00, 0x6d, 0x00, 0x01, 0x00, 0x31, 0x00, 0x00, 0x00, 0x05, 0x40,
0x70, 0x75, 0x73, 0x68, 0x00, 0x00, 0x02, 0x60, 0x00, 0x00, 0x02, 0x60,
0x01, 0x00, 0x0d, 0x50, 0x04, 0x31, 0x30, 0x30, 0x88, 0x1d, 0x00, 0x6b,
0x12, 0x6f, 0x67, 0x01, 0x60, 0x00, 0x18, 0x50, 0x04, 0x01, 0x04, 0x70,
0x02, 0x01, 0x60, 0x89, 0x01, 0x00, 0x01, 0x78, 0x01, 0xa0, 0x89, 0x00,
0x00, 0x01, 0x12, 0x78, 0x02, 0x67, 0x76, 0xea, 0x39, 0x00, 0x3d, 0x00,
0x02, 0x00, 0x19, 0x00, 0x01, 0x00, 0x08, 0xc0, 0x05, 0x00, 0x05, 0x00,
0x31, 0x00, 0x41, 0x00
};
unsigned int main_mvm_bc_len = 124;
static mvm_VM* vm;
#define IMPORT_COUNT 1
static const uint16_t importIDs[IMPORT_COUNT] = { 0, 1 };
mvm_TeError print(mvm_VM* vm, mvm_HostFunctionID funcID, mvm_Value* result, mvm_Value* args, uint8_t argCount);
mvm_TeError mvm_fgets(mvm_VM* vm, mvm_HostFunctionID funcID, mvm_Value* result, mvm_Value* args, uint8_t argCount);
static struct {
mvm_Value main;
} imports;
mvm_TfHostFunction exports[] = {
&print,
&mvm_fgets,
NULL
};
mvm_TeError print(mvm_VM* vm, mvm_HostFunctionID funcID, mvm_Value* result, mvm_Value* args, uint8_t argCount) {
assert(argCount == 1);
printf("argc: %d\n", argCount);
size_t len;
// XXX failure occurs here, if print(fgets()) is called
const char *str = mvm_toStringUtf8(vm, args[0], &len);
if(str[len - 1] == '\0') {
printf("%s\n", str);
} else {
printf("%.*s\n", len, str);
}
return MVM_E_SUCCESS;
}
mvm_TeError mvm_fgets(mvm_VM* vm, mvm_HostFunctionID funcID, mvm_Value* result, mvm_Value* args, uint8_t argCount) {
char c = fgetc(stdin);
*result = mvm_newString(vm, &c, 1);
mvm_runGC(vm, true);
return MVM_E_SUCCESS;
}
static mvm_TeError resolveHostFunction(mvm_HostFunctionID funcID, void* context, mvm_TfHostFunction* out) {
if(exports[funcID] != NULL) {
*out = exports[funcID];
return MVM_E_SUCCESS;
}
return MVM_E_UNRESOLVED_IMPORT;
}
void main() {
mvm_TeError err;
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
err = mvm_restore(&vm, main_mvm_bc, main_mvm_bc_len, NULL, &resolveHostFunction);
err = mvm_resolveExports(vm, importIDs, (mvm_Value*)&imports, IMPORT_COUNT);
// call main.js#main()
mvm_call(vm, imports.main, NULL, 0, 0);
}