r16/emu/cpu/stack.c

46 lines
1.0 KiB
C
Raw Permalink Normal View History

2024-04-19 09:05:10 +00:00
#include "./stack.h"
2024-04-22 11:08:57 +00:00
#include "./register.h"
2024-04-19 10:08:32 +00:00
#include <stdlib.h>
#include <stdio.h>
2024-04-22 11:08:57 +00:00
#include <stdbool.h>
void LogStack(bool onlyUpToSP, bool pointOutSP)
{
char *pointer = "->";
char *nointer = " ";
for (int i = 0; i < (onlyUpToSP ? GetRegister(SP).u : STACK_SIZE); i++)
{
printf("%s 0x%x: 0x%x\n", ((pointOutSP && i == GetRegister(SP).u) ? pointer : nointer),
i, GetValue((r16_int){ STACK_LOCATION + i }).u);
}
}
2024-04-19 09:05:10 +00:00
2024-04-19 10:08:32 +00:00
r16_int StackPop()
2024-04-19 09:05:10 +00:00
{
#ifdef DO_STACK_CHECKS
2024-04-19 10:08:32 +00:00
if (GetRegister(SP).u == 0)
{
fprintf(stderr, "STACK UNDERFLOW\n");
exit(-1);
}
2024-04-19 09:05:10 +00:00
#endif
2024-04-19 10:08:32 +00:00
SetRegister(SP, (r16_int){ GetRegister(SP).u - 1 });
return GetValue((r16_int){ GetRegister(SP).u + STACK_LOCATION });
2024-04-19 09:05:10 +00:00
}
2024-04-19 10:08:32 +00:00
void StackPush(r16_int value)
2024-04-19 09:05:10 +00:00
{
2024-04-19 10:08:32 +00:00
#ifdef DO_STACK_CHECKS
if (GetRegister(SP).u >= STACK_SIZE)
{
fprintf(stderr, "STACK OVERFLOW\n");
exit(-1);
}
#endif
2024-04-19 09:05:10 +00:00
2024-04-19 10:08:32 +00:00
SetValue((r16_int){ GetRegister(SP).u + STACK_LOCATION }, value);
SetRegister(SP, (r16_int){ GetRegister(SP).u + 1 });
2024-04-19 09:05:10 +00:00
}