wraith-lang/src/stack.c

66 lines
1.8 KiB
C
Raw Normal View History

2021-04-18 22:29:54 +00:00
#include <stdint.h>
#include <stdlib.h>
#include "stack.h"
Stack* CreateStack()
{
2021-04-21 06:51:26 +00:00
int32_t i;
2021-04-18 22:29:54 +00:00
Stack *stack = (Stack*) malloc(sizeof(Stack));
stack->stackCapacity = 4;
stack->stackFrames = (StackFrame*) malloc(sizeof(StackFrame) * stack->stackCapacity);
for (i = 0; i < stack->stackCapacity; i += 1)
{
2021-04-20 17:47:40 +00:00
stack->stackFrames[i].nodes = NULL;
stack->stackFrames[i].nodeCapacity = 0;
stack->stackFrames[i].nodeCount = 0;
2021-04-18 22:29:54 +00:00
}
stack->stackIndex = 0;
2021-04-21 06:51:26 +00:00
PushStackFrame(stack);
2021-04-18 22:29:54 +00:00
return stack;
}
void PushStackFrame(Stack *stack)
{
stack->stackIndex += 1;
if (stack->stackIndex == stack->stackCapacity)
{
stack->stackCapacity += 1;
stack->stackFrames = (StackFrame*) realloc(stack->stackFrames, sizeof(StackFrame) * stack->stackCapacity);
2021-04-21 06:51:26 +00:00
stack->stackFrames[stack->stackIndex].nodes = NULL;
2021-04-20 17:47:40 +00:00
stack->stackFrames[stack->stackIndex].nodeCapacity = 0;
2021-04-21 06:51:26 +00:00
stack->stackFrames[stack->stackIndex].nodeCount = 0;
2021-04-18 22:29:54 +00:00
}
2021-04-20 17:47:40 +00:00
stack->stackFrames[stack->stackIndex].nodeCount = 0;
2021-04-18 22:29:54 +00:00
}
void PopStackFrame(Stack *stack)
{
stack->stackIndex -= 1;
}
2021-04-20 17:47:40 +00:00
void AddNode(Stack *stack, Node *statementNode)
2021-04-18 22:29:54 +00:00
{
StackFrame *stackFrame = &stack->stackFrames[stack->stackIndex];
2021-04-20 17:47:40 +00:00
if (stackFrame->nodeCount == stackFrame->nodeCapacity)
2021-04-18 22:29:54 +00:00
{
2021-04-20 17:47:40 +00:00
stackFrame->nodeCapacity += 1;
2021-04-21 02:00:18 +00:00
stackFrame->nodes = (Node**) realloc(stackFrame->nodes, sizeof(Node*) * stackFrame->nodeCapacity);
2021-04-18 22:29:54 +00:00
}
2021-04-20 17:47:40 +00:00
stackFrame->nodes[stackFrame->nodeCount] = statementNode;
stackFrame->nodeCount += 1;
2021-04-18 22:29:54 +00:00
}
2021-04-20 17:47:40 +00:00
Node** GetNodes(Stack *stack, uint32_t *pCount)
2021-04-18 22:29:54 +00:00
{
2021-04-21 06:51:26 +00:00
if (stack->stackIndex < 0) {
*pCount= 0;
return NULL;
}
2021-04-20 17:47:40 +00:00
*pCount = stack->stackFrames[stack->stackIndex].nodeCount;
return stack->stackFrames[stack->stackIndex].nodes;
2021-04-18 22:29:54 +00:00
}