Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "defs.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- static uint16_t g_mem[0x10000];
- static uint16_t g_reg[4];
- uint16_t getSrcVal(uint16_t src, uint16_t srcType)
- {
- switch(srcType)
- {
- case Const : return src;
- case Reg : return g_reg[src];
- case Mem : return g_mem[src];
- default : return 0;
- }
- }
- void setDstVal(uint16_t dst, uint16_t dstType, uint16_t val)
- {
- switch(dstType)
- {
- case Reg: g_reg[dst] = val; break;
- case Mem: g_mem[dst] = val; break;
- }
- }
- int main(int argc, char **argv)
- {
- command_t *prog;
- size_t size;
- {
- FILE *file = fopen(argv[1], "rb");
- fseek(file, 0, SEEK_END);
- size = ftell(file) / sizeof(command_t);
- rewind(file);
- prog = calloc(size, sizeof(command_t));
- fread(prog, sizeof(command_t), size, file);
- fclose(file);
- }
- for(command_t *cmd = prog; cmd < prog + size; cmd++)
- {
- switch(cmd->opCode)
- {
- case Mov:
- {
- uint16_t srcVal = getSrcVal(cmd->src, cmd->srcType);
- setDstVal(cmd->dst, cmd->dstType, srcVal);
- }
- break;
- #define APPLYOP(apply, op) \
- { \
- uint16_t dstVal = getSrcVal(cmd->dst, cmd->dstType); \
- uint16_t srcVal = getSrcVal(cmd->src, cmd->srcType); \
- uint16_t result = apply(op, dstVal, srcVal); \
- setDstVal(cmd->dst, cmd->dstType, result); \
- } \
- break;
- #define UNARY(op, dst, src) (op src)
- #define BINARY(op, dst, src) (dst op src)
- #define BINARYOFNOT(op, dst, src) (!dst op !src)
- case Add : APPLYOP(BINARY , +);
- case Sub : APPLYOP(BINARY , -);
- case Mul : APPLYOP(BINARY , *);
- case Div : APPLYOP(BINARY , /);
- case Mod : APPLYOP(BINARY , %);
- case Not : APPLYOP(UNARY , !);
- case And : APPLYOP(BINARY , &&);
- case Or : APPLYOP(BINARY , ||);
- case Xor : APPLYOP(BINARYOFNOT , !=);
- case BNot : APPLYOP(UNARY , ~);
- case BAnd : APPLYOP(BINARY , &);
- case BOr : APPLYOP(BINARY , |);
- case BXor : APPLYOP(BINARYOFNOT , ^);
- #undef BINARYOFNOT
- #undef BINARY
- #undef UNARY
- #undef APPLYOP
- case Jmp:
- {
- uint16_t addr = getSrcVal(cmd->dst, cmd->dstType);
- cmd = &prog[addr-1];
- }
- break;
- case JmpIf:
- {
- uint16_t addr = getSrcVal(cmd->dst, cmd->dstType);
- uint16_t cond = getSrcVal(cmd->src, cmd->srcType);
- if(cond)
- cmd = &prog[addr-1];
- }
- break;
- case Read:
- {
- setDstVal(cmd->dst, cmd->dstType, getchar());
- }
- break;
- case Write:
- {
- putchar(getSrcVal(cmd->src, cmd->srcType));
- }
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment