This commit is contained in:
Nishi 2026-05-09 03:16:12 +09:00
commit d951a0bceb
Signed by: nishi
GPG key ID: 27EF69B208EB9343
15 changed files with 381 additions and 90 deletions

View file

@ -4,12 +4,7 @@ duk_context* js_ctx;
LOAD(js_core);
LOAD(js_cmdline);
static duk_ret_t js_console_log(duk_context* self) {
printf("%s\n", duk_to_string(self, 0));
return 0;
}
LOAD(js_end);
static void js_argv_init(int argc, char** argv) {
int arr;
@ -28,57 +23,15 @@ static void js_argv_init(int argc, char** argv) {
duk_pop(js_ctx);
}
static void js_console_init(void) {
int obj;
duk_push_global_object(js_ctx);
obj = duk_push_object(js_ctx);
duk_push_c_function(js_ctx, js_console_log, 1);
duk_put_prop_string(js_ctx, obj, "log");
duk_put_prop_string(js_ctx, 0, "console");
duk_pop(js_ctx);
}
static duk_ret_t js_process_exit(duk_context* self) {
duk_idx_t argc = duk_get_top(self);
int ex;
if(argc > 1) {
return duk_error(self, DUK_ERR_TYPE_ERROR, "needs 0 or 1 argument(s)");
}
if(argc == 1) {
ex = duk_to_number(self, 0);
} else {
ex = 0;
}
exit(ex);
}
static void js_process_init(void) {
int obj;
duk_push_global_object(js_ctx);
obj = duk_push_object(js_ctx);
duk_push_c_function(js_ctx, js_process_exit, DUK_VARARGS);
duk_put_prop_string(js_ctx, obj, "exit");
duk_put_prop_string(js_ctx, 0, "process");
duk_pop(js_ctx);
}
int js_init(int argc, char** argv) {
int st;
js_ctx = duk_create_heap_default();
js_argv_init(argc, argv);
js_console_init();
js_process_init();
js_fs_init();
if(duk_peval_lstring(js_ctx, js_core, js_core_len) != 0) {
printf("error: js/core.js: %s\n", duk_safe_to_string(js_ctx, -1));
@ -93,6 +46,8 @@ int js_init(int argc, char** argv) {
JS;
#undef X
if((st = js_run("pmake.js")) != 0) return st;
if(duk_peval_lstring(js_ctx, js_cmdline, js_cmdline_len) != 0) {
printf("error: js/cmdline.js: %s\n", duk_safe_to_string(js_ctx, -1));
return 1;
@ -101,6 +56,38 @@ int js_init(int argc, char** argv) {
return 0;
}
int js_run(const char* file) {
FILE* f;
char* buffer;
int len;
if((f = fopen(file, "rb")) == NULL) {
printf("No PMake script (pmake.js) found!\n");
return 1;
}
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, 0, SEEK_SET);
buffer = malloc(len);
fread(buffer, 1, len, f);
if(duk_peval_lstring(js_ctx, buffer, len) != 0) {
printf("error: %s: %s\n", file, duk_safe_to_string(js_ctx, -1));
free(buffer);
fclose(f);
return 1;
}
free(buffer);
fclose(f);
return 0;
}
void js_uninit(void) {
duk_destroy_heap(js_ctx);
}