You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.c 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "vm/vm.h"
  2. #include "vm/print.h"
  3. #include "parse/parse.h"
  4. #include "parse/lex.h"
  5. #include "io.h"
  6. #include "bitset.h"
  7. #include <stdio.h>
  8. #include <string.h>
  9. void step_through(struct l2_vm *vm) {
  10. printf("=====\n\nInitial state:\n");
  11. l2_vm_print_state(vm);
  12. char buf[16];
  13. while ((enum l2_opcode)vm->ops[vm->iptr] != L2_OP_HALT) {
  14. size_t iptr = vm->iptr;
  15. printf("\n======\n\n(%d) Will run instr: ", vm->iptr);
  16. l2_vm_print_op(vm->ops, vm->opcount, &iptr);
  17. fgets(buf, sizeof(buf), stdin);
  18. l2_vm_step(vm);
  19. l2_vm_print_state(vm);
  20. }
  21. }
  22. int main(int argc, char **argv) {
  23. if (argc != 1 && argc != 2) {
  24. fprintf(stderr, "Usage: %s [file]\n", argv[0]);
  25. return 1;
  26. }
  27. FILE *inf;
  28. if (argc == 1 || (argc == 2 && strcmp(argv[1], "-") == 0)) {
  29. inf = stdin;
  30. } else {
  31. inf = fopen(argv[1], "r");
  32. }
  33. // Init lexer with its input reader
  34. struct l2_io_file_reader r;
  35. r.r.read = l2_io_file_read;
  36. r.f = inf;
  37. struct l2_lexer lexer;
  38. l2_lexer_init(&lexer, &r.r);
  39. // Init gen with its output writer
  40. struct l2_io_mem_writer w = {0};
  41. w.w.write = l2_io_mem_write;
  42. struct l2_generator gen;
  43. l2_gen_init(&gen, &w.w);
  44. struct l2_parse_error err;
  45. if (l2_parse_program(&lexer, &gen, &err) < 0) {
  46. fprintf(stderr, "Parse error: %s:%i:%i: %s\n",
  47. (argc == 2 ? argv[1] : "-"), err.line, err.ch, err.message);
  48. l2_gen_free(&gen);
  49. fclose(inf);
  50. return 1;
  51. }
  52. l2_gen_free(&gen);
  53. fclose(inf);
  54. printf("Generated bytecode:\n");
  55. l2_vm_print_bytecode((l2_word *)w.mem, w.len / sizeof(l2_word));
  56. fprintf(stderr, "\n");
  57. struct l2_vm vm;
  58. l2_vm_init(&vm, (void *)w.mem, w.len / sizeof(l2_word));
  59. step_through(&vm);
  60. free(w.mem);
  61. printf("State after executing:\n");
  62. l2_vm_print_state(&vm);
  63. while (l2_vm_gc(&vm));
  64. printf("State after GC:\n");
  65. l2_vm_print_state(&vm);
  66. l2_vm_free(&vm);
  67. }