/* * cat/backend/c.c -- the C backend (see cat/backend/c.h). * * Naming rule: symbols here are cat_backend_c_* / CAT_BACKEND_C_*. * * A compiled CAT_BYTECODE_Function is written out as a C translation * unit that rebuilds the bytecode at startup and runs it on the * catscript runtime. The result is a native binary produced by `cc` * with no compiler inside it: parsing/compilation happen ahead of time. */ #include "cat/backend/c.h" #include "cat/bytecode.h" #include "cat/error.h" #include "cat/types/number.h" #include "cat/types/ascii_text.h" #include #include #include #include /* opcode mnemonics, for readable comments in the generated C. */ static const char *c_op_name(unsigned char op) { static const char *names[] = { "NOP", "CONST", "EMPTY", "TRUE", "FALSE", "GETLOCAL", "SETLOCAL", "GETGLOBAL", "SETGLOBAL", "ADD", "SUB", "MUL", "DIV", "REM", "NEG", "NOT", "EQ", "NE", "LT", "LE", "GT", "GE", "GETATTR", "SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF", "JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE", "GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX", "YIELD", "NEXT", "TRYSETUP", "TRYEND", "RAISE", "FORNEXT", "PRINTEXPR", "IS" }; if (op < sizeof(names) / sizeof(names[0])) return names[op]; return "?"; } /* Write `s` as the body of a C string literal, octal-escaping anything * that is not safe to emit verbatim. Three-digit octal escapes never * bleed into following characters. */ static void c_escape(FILE *out, const char *s) { const unsigned char *p = (const unsigned char *)s; for (; p != NULL && *p != '\0'; p++) { unsigned char ch = *p; if (ch == '"' || ch == '\\' || ch < 0x20 || ch >= 0x7f) fprintf(out, "\\%03o", ch); else fputc(ch, out); } } /* Number of functions in a prototype subtree (including itself). */ static int c_count_fns(CAT_BYTECODE_Function *fn) { int n = 1, i; for (i = 0; i < fn->nprotos; i++) n += c_count_fns(fn->protos[i]); return n; } /* Emit the C expression that recreates a constant value. */ static void c_emit_const(FILE *out, CAT_VALUE_Value *v) { if (v == NULL) { fprintf(out, "cat_types_empty()"); return; } if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v; if (n->is_float) fprintf(out, "cat_types_float_new(%.17g)", n->f); else fprintf(out, "cat_types_int_new(%lldLL)", n->i); return; } if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_TEXT) { fprintf(out, "cat_types_ascii_text_new(\""); c_escape(out, cat_types_text_bytes(v)); fprintf(out, "\")"); return; } if (v->vtable != NULL && v->vtable->kind == CAT_VALUE_KIND_BOOL) { int t = 1; CAT_ERROR_Error e; cat_error_clear(&e); cat_value_truthy(v, &t, &e); fprintf(out, "%s", t ? "cat_types_bool_true()" : "cat_types_bool_false()"); return; } /* anything else cannot appear as a literal constant in practice */ fprintf(out, "cat_types_empty()"); } /* Emit the definition body for the function numbered `idx`. Child * functions are numbered in pre-order, so child i's index is * idx + 1 + (size of the subtrees before it). */ static void c_emit_fn(FILE *out, CAT_BYTECODE_Function *fn, int idx) { int i; int child; fprintf(out, "static CAT_BYTECODE_Function *cat_prog_fn_%d(void)\n{\n", idx); fprintf(out, "\tCAT_BYTECODE_Function *fn = " "cat_bytecode_function_new(\""); c_escape(out, fn->name ? fn->name : ""); fprintf(out, "\");\n\n"); fprintf(out, "\tfn->nparams = %d;\n\tfn->nlocals = %d;\n", fn->nparams, fn->nlocals); fprintf(out, "\tfn->is_generator = %d;\n\n", fn->is_generator); for (i = 0; i < fn->nconsts; i++) { fprintf(out, "\tcat_bytecode_add_const(fn, "); c_emit_const(out, fn->consts[i].value); fprintf(out, ");\n"); } if (fn->nconsts > 0) fprintf(out, "\n"); child = idx + 1; for (i = 0; i < fn->nprotos; i++) { fprintf(out, "\tcat_bytecode_add_proto(fn, cat_prog_fn_%d());\n", child); child += c_count_fns(fn->protos[i]); } if (fn->nprotos > 0) fprintf(out, "\n"); for (i = 0; i < fn->ncode; i++) { CAT_BYTECODE_Instr *in = &fn->code[i]; fprintf(out, "\tcat_bytecode_emit(fn, %d, %d, %d, %d, %d);" " /* %s */\n", in->op, in->a, in->b, in->c, in->line, c_op_name(in->op)); } fprintf(out, "\treturn fn;\n}\n\n"); } /* Pre-order forward declarations. */ static void c_emit_decls(FILE *out, CAT_BYTECODE_Function *fn, int *next) { int self = (*next)++; int i; fprintf(out, "static CAT_BYTECODE_Function *cat_prog_fn_%d(void);\n", self); for (i = 0; i < fn->nprotos; i++) c_emit_decls(out, fn->protos[i], next); } /* Pre-order definitions (mirrors c_emit_decls). */ static void c_emit_defs(FILE *out, CAT_BYTECODE_Function *fn, int *next) { int self = (*next)++; int i; c_emit_fn(out, fn, self); for (i = 0; i < fn->nprotos; i++) c_emit_defs(out, fn->protos[i], next); } /* Directory holding the running executable, or NULL. */ static char *c_exe_dir(void) { char buf[4096]; ssize_t n; char *slash; n = readlink("/proc/self/exe", buf, sizeof(buf) - 1); if (n <= 0) return NULL; buf[n] = '\0'; slash = strrchr(buf, '/'); if (slash == NULL) return NULL; *slash = '\0'; return strdup(buf); } int cat_backend_c_emit(CAT_BYTECODE_Function *fn, const char *module_name, const char *module_path, FILE *out) { int next; if (fn == NULL || out == NULL) return -1; fprintf(out, "/* generated by catscript -- C backend (AOT). */\n"); fprintf(out, "#include \"cat/vm.h\"\n"); fprintf(out, "#include \"cat/bytecode.h\"\n"); fprintf(out, "#include \"cat/module.h\"\n"); fprintf(out, "#include \"cat/error.h\"\n"); fprintf(out, "#include \"cat/stdlib/stdlib.h\"\n"); fprintf(out, "#include \"cat/stdlib/build.h\"\n"); fprintf(out, "#include \"cat/types/number.h\"\n"); fprintf(out, "#include \"cat/types/int.h\"\n"); fprintf(out, "#include \"cat/types/float.h\"\n"); fprintf(out, "#include \"cat/types/ascii_text.h\"\n"); fprintf(out, "#include \"cat/types/bool.h\"\n"); fprintf(out, "#include \"cat/types/empty.h\"\n\n"); fprintf(out, "#include \n\n"); next = 0; fprintf(out, "/* function prototypes */\n"); c_emit_decls(out, fn, &next); fprintf(out, "\n"); next = 0; c_emit_defs(out, fn, &next); fprintf(out, "int main(void)\n{\n"); fprintf(out, "\tCAT_VM_State *vm;\n"); fprintf(out, "\tCAT_BYTECODE_Function *top;\n"); fprintf(out, "\tCAT_VALUE_Value *out = NULL;\n"); fprintf(out, "\tint rc;\n\n"); fprintf(out, "\tvm = cat_vm_new();\n"); fprintf(out, "\tif (vm == NULL)\n\t\treturn 1;\n"); fprintf(out, "\tcat_stdlib_stdlib_install(vm);\n"); fprintf(out, "\tcat_stdlib_build_install(vm);\n"); fprintf(out, "\tcat_module_enter(vm, \""); c_escape(out, module_name ? module_name : ""); fprintf(out, "\", "); if (module_path != NULL) { fprintf(out, "\""); c_escape(out, module_path); fprintf(out, "\""); } else { fprintf(out, "NULL"); } fprintf(out, ");\n\n"); fprintf(out, "\ttop = cat_prog_fn_0();\n"); fprintf(out, "\trc = cat_vm_run(vm, top, &out);\n"); fprintf(out, "\tif (rc != 0)\n"); fprintf(out, "\t\tfprintf(stderr, \"catscript: %%s\\n\", " "vm->err.message);\n"); fprintf(out, "\tcat_bytecode_function_free(top);\n"); fprintf(out, "\tcat_vm_free(vm);\n"); fprintf(out, "\treturn rc != 0;\n}\n"); return 0; } int cat_backend_c_compile(CAT_BYTECODE_Function *fn, const char *module_name, const char *module_path, const char *outpath, char *errbuf, size_t errsz) { char tmpl[] = "/tmp/catscript-aot-XXXXXX.c"; char cmd[9216]; char inc[4096]; char lib[4096]; char *dir; FILE *f; int fd; int st; if (errbuf != NULL && errsz > 0) errbuf[0] = '\0'; fd = mkstemps(tmpl, 2); if (fd < 0) return -1; f = fdopen(fd, "w"); if (f == NULL) { close(fd); return -1; } if (cat_backend_c_emit(fn, module_name, module_path, f) != 0) { fclose(f); unlink(tmpl); return -1; } fclose(f); dir = c_exe_dir(); if (dir == NULL) { unlink(tmpl); if (errbuf != NULL) snprintf(errbuf, errsz, "cannot locate the catscript runtime"); return -1; } snprintf(inc, sizeof(inc), "%s/../../include", dir); snprintf(lib, sizeof(lib), "%s/libcatscript.a", dir); if (access(lib, R_OK) != 0) { unlink(tmpl); free(dir); if (errbuf != NULL) snprintf(errbuf, errsz, "runtime archive missing at %s", lib); return -1; } snprintf(cmd, sizeof(cmd), "cc -std=c11 -O2 -D_DEFAULT_SOURCE -I'%s' -o '%s' '%s' '%s' " "-lm -lffi -ldl 2>&1", inc, outpath, tmpl, lib); st = system(cmd); unlink(tmpl); free(dir); if (st != 0) { if (errbuf != NULL) snprintf(errbuf, errsz, "C compiler failed (status %d)", st); return -1; } return 0; }