1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- #include "vm/vm.h"
- #include "vm/print.h"
- #include "parse/parse.h"
- #include "parse/lex.h"
- #include "io.h"
- #include "bitset.h"
-
- #include <stdio.h>
- #include <string.h>
-
- void step_through(struct l2_vm *vm) {
- printf("=====\n\nInitial state:\n");
- l2_vm_print_state(vm);
-
- char buf[16];
- while ((enum l2_opcode)vm->ops[vm->iptr] != L2_OP_HALT) {
- size_t iptr = vm->iptr;
- printf("\n======\n\n(%d) Will run instr: ", vm->iptr);
- l2_vm_print_op(vm->ops, vm->opcount, &iptr);
- fgets(buf, sizeof(buf), stdin);
- l2_vm_step(vm);
- l2_vm_print_state(vm);
- }
- }
-
- int main(int argc, char **argv) {
- if (argc != 1 && argc != 2) {
- fprintf(stderr, "Usage: %s [file]\n", argv[0]);
- return 1;
- }
-
- FILE *inf;
- if (argc == 1 || (argc == 2 && strcmp(argv[1], "-") == 0)) {
- inf = stdin;
- } else {
- inf = fopen(argv[1], "r");
- }
-
- // Init lexer with its input reader
- struct l2_io_file_reader r;
- r.r.read = l2_io_file_read;
- r.f = inf;
- struct l2_lexer lexer;
- l2_lexer_init(&lexer, &r.r);
-
- // Init gen with its output writer
- struct l2_io_mem_writer w = {0};
- w.w.write = l2_io_mem_write;
- struct l2_generator gen;
- l2_gen_init(&gen, &w.w);
-
- struct l2_parse_error err;
- if (l2_parse_program(&lexer, &gen, &err) < 0) {
- fprintf(stderr, "Parse error: %s:%i:%i: %s\n",
- (argc == 2 ? argv[1] : "-"), err.line, err.ch, err.message);
- l2_gen_free(&gen);
- fclose(inf);
- return 1;
- }
-
- l2_gen_free(&gen);
- fclose(inf);
-
- printf("Generated bytecode:\n");
- l2_vm_print_bytecode((l2_word *)w.mem, w.len / sizeof(l2_word));
- fprintf(stderr, "\n");
-
- struct l2_vm vm;
- l2_vm_init(&vm, (void *)w.mem, w.len / sizeof(l2_word));
-
- step_through(&vm);
- free(w.mem);
-
- printf("State after executing:\n");
- l2_vm_print_state(&vm);
-
- while (l2_vm_gc(&vm));
-
- printf("State after GC:\n");
- l2_vm_print_state(&vm);
-
- l2_vm_free(&vm);
- }
|