aboutsummaryrefslogtreecommitdiff
path: root/vmrun/src/main.c
blob: 0bdd16f12af54309046f120a2710f57fa7a4f9d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <vm.h>

#include <stdbool.h>
#include <stdio.h>
#include <string.h>

typedef enum CommandType {
  ExitSession,
  PrintStack,
} CommandType;

typedef struct Command {
  CommandType type;
} Command;

static bool read_command(char line[], Command* pCmd) {
  static const char* delim = " \n";

  const char* cmd = strtok(line, delim);
  if (strcmp(cmd, "exit") == 0) {
    *pCmd = (Command){.type = ExitSession};
    return true;
  } else if (strcmp(cmd, "print_stack") == 0) {
    *pCmd = (Command){.type = PrintStack};
    return true;
  }
  return false;
}

/// Runs a command.
///
/// Returns true unless on ExitSession.
static bool run_command(Vm* vm, Command cmd) {
  switch (cmd.type) {
  case ExitSession:
    return false;
  case PrintStack:
    vm_print_stack(vm);
    break;
  }
  return true;
}

int main() {
  Vm* vm = vm_new();
  if (!vm) {
    fprintf(stderr, "Failed to create VM\n");
    return 1;
  }

  Command cmd;
  bool    should_continue = true;
  char    line[128];

  while (should_continue && fgets(line, sizeof(line), stdin)) {
    if (read_command(line, &cmd)) {
      should_continue = run_command(vm, cmd);
    } else {
      fprintf(stderr, "Unknown command\n");
    }
  }

  vm_del(&vm);
  return 0;
}