Advertisement
Guest User

basic_vm.c

a guest
Oct 6th, 2018
772
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. bool running = true;   //check running status
  5. int ip = 0;                     //Instuction Pointer
  6. int sp = -1;                    //Stack Pointer
  7.  
  8. int stack[256];             //VM's Ram
  9.  
  10. typedef enum {
  11.         PSH,
  12.         ADD,
  13.         POP,
  14.         HLT
  15. }   InstructionSet;             //supported opcodes for VM
  16.  
  17. const int program[] = {
  18.     PSH, 5,
  19.     PSH, 6,
  20.     ADD,
  21.     POP,
  22.     HLT
  23. };                              //code to be executed inside VM
  24.  
  25. int fetch() {
  26.     return program[ip];
  27. }
  28.  
  29. void eval(int instr) {              //VM implementation
  30.     switch(instr) {
  31.         case HLT: {
  32.             running=false;
  33.             printf("Done\n");
  34.             break;
  35.         }
  36.         case PSH: {
  37.             sp++;
  38.             stack[sp] = program[++ip];
  39.             break;
  40.         }
  41.         case POP: {
  42.             int val_popped = stack[sp--];
  43.             printf("popped %d \n",val_popped);
  44.             break;
  45.         }
  46.         case ADD: {
  47.             int a=stack[sp--];
  48.             int b=stack[sp--];
  49.             int result = b+a;
  50.             sp++;
  51.             stack[sp]=result;
  52.             break;
  53.         }
  54.     }
  55. }
  56.  
  57. int main() {
  58.     while(running) {
  59.         eval(fetch());
  60.         ip++;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement