wraith-lang/stack.c

58 lines
1.6 KiB
C

#include <stdint.h>
#include <stdlib.h>
#include "stack.h"
Stack* CreateStack()
{
uint32_t i;
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)
{
stack->stackFrames[i].nodes = NULL;
stack->stackFrames[i].nodeCapacity = 0;
stack->stackFrames[i].nodeCount = 0;
}
stack->stackIndex = 0;
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);
stack->stackFrames[stack->stackIndex].nodeCapacity = 0;
}
stack->stackFrames[stack->stackIndex].nodeCount = 0;
}
void PopStackFrame(Stack *stack)
{
stack->stackIndex -= 1;
}
void AddNode(Stack *stack, Node *statementNode)
{
StackFrame *stackFrame = &stack->stackFrames[stack->stackIndex];
if (stackFrame->nodeCount == stackFrame->nodeCapacity)
{
stackFrame->nodeCapacity += 1;
stackFrame->nodes = (Node**) realloc(stackFrame->nodes, sizeof(Node*) * stackFrame->nodeCapacity);
}
stackFrame->nodes[stackFrame->nodeCount] = statementNode;
stackFrame->nodeCount += 1;
}
Node** GetNodes(Stack *stack, uint32_t *pCount)
{
*pCount = stack->stackFrames[stack->stackIndex].nodeCount;
return stack->stackFrames[stack->stackIndex].nodes;
}