diff --git a/Makefile b/Makefile index fb72f74..7cdee35 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ ECHO=echo -e CFLAGS=-Wall -Werror -std=gnu99 -O0 -g -Iinclude LIBS=-lSDL2 -FILES=build/main.o build/mem.o +FILES=build/main.o build/mem.o build/stack.o OUT=bin/chip8.out all: $(FILES) @@ -18,6 +18,10 @@ build/mem.o: src/mem.c @$(ECHO) "CC\t\t"$< @$(CC) $(CFLAGS) $< -c -o $@ $(LIBS) +build/stack.o: src/stack.c + @$(ECHO) "CC\t\t"$< + @$(CC) $(CFLAGS) $< -c -o $@ $(LIBS) + run: all @$(ECHO) "Runing the Chip8 compiler" @$(OUT) diff --git a/include/chip8.h b/include/chip8.h index 1f2746d..8dda08f 100644 --- a/include/chip8.h +++ b/include/chip8.h @@ -4,11 +4,13 @@ #include "config.h" #include "mem.h" #include "registers.h" +#include "stack.h" struct chip8 { struct chip8_memory memory; struct chip8_registers registers; + struct chip8_stack stack; }; #endif diff --git a/include/config.h b/include/config.h index 84e3a9d..7d4b4fa 100644 --- a/include/config.h +++ b/include/config.h @@ -9,5 +9,6 @@ #define CHIP8_DISPLAY_HEIGHT 32 #define CHIP8_TOTAL_DATA_REGISTERS 16 +#define CHIP8_TOTAL_STACK_DEPTH 16 #endif diff --git a/include/stack.h b/include/stack.h new file mode 100644 index 0000000..e671dac --- /dev/null +++ b/include/stack.h @@ -0,0 +1,15 @@ +#ifndef __STACK_H +#define __STACK_H + +#include "config.h" + +struct chip8; +struct chip8_stack +{ + unsigned short stack[CHIP8_TOTAL_STACK_DEPTH]; +}; + +void chip8_stack_push (struct chip8 *chip8, unsigned short val); +unsigned short chip8_stack_pop (struct chip8 *chip8); + +#endif diff --git a/src/main.c b/src/main.c index a667faf..ca0416d 100644 --- a/src/main.c +++ b/src/main.c @@ -5,9 +5,13 @@ int main (int argc, char **argv) { - struct chip8 chip8 = { 0 }; - chip8_memory_set (&chip8.memory, 50, 'Z'); - printf ("%c\n", chip8_memory_get (&chip8.memory, 50)); + struct chip8 chip8; + chip8.registers.SP = 0; + chip8_stack_push (&chip8, 0xff); + chip8_stack_push (&chip8, 0xaa); + + printf ("%x\n", chip8_stack_pop (&chip8)); + printf ("%x\n", chip8_stack_pop (&chip8)); SDL_Init (SDL_INIT_EVERYTHING); SDL_Window *window = SDL_CreateWindow ( diff --git a/src/stack.c b/src/stack.c new file mode 100644 index 0000000..812cb4b --- /dev/null +++ b/src/stack.c @@ -0,0 +1,29 @@ +#include "stack.h" +#include "chip8.h" + +#include + +static void +chip8_stack_in_bounds (struct chip8 *chip8) +{ + assert (chip8->registers.SP < sizeof (chip8->stack.stack)); +} + +void +chip8_stack_push (struct chip8 *chip8, unsigned short val) +{ + chip8->registers.SP += 1; + chip8_stack_in_bounds (chip8); + + chip8->stack.stack[chip8->registers.SP] = val; +} + +unsigned short +chip8_stack_pop (struct chip8 *chip8) +{ + chip8_stack_in_bounds (chip8); + + unsigned short result = chip8->stack.stack[chip8->registers.SP]; + chip8->registers.SP -= 1; + return result; // we don't set the program counter +}