wraith-lang/stack.c

81 lines
2.6 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()
{
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].statements = NULL;
stack->stackFrames[i].statementCapacity = 0;
stack->stackFrames[i].statementCount = 0;
stack->stackFrames[i].declarations = NULL;
stack->stackFrames[i].declarationCapacity = 0;
stack->stackFrames[i].declarationCount = 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].statementCapacity = 0;
stack->stackFrames[stack->stackIndex].declarationCapacity = 0;
}
stack->stackFrames[stack->stackIndex].statementCount = 0;
stack->stackFrames[stack->stackIndex].declarationCount = 0;
}
void PopStackFrame(Stack *stack)
{
stack->stackIndex -= 1;
}
void AddStatement(Stack *stack, Node *statementNode)
{
StackFrame *stackFrame = &stack->stackFrames[stack->stackIndex];
if (stackFrame->statementCount == stackFrame->statementCapacity)
{
stackFrame->statementCapacity += 1;
stackFrame->statements = (Node**) realloc(stackFrame->statements, stackFrame->statementCapacity);
}
stackFrame->statements[stackFrame->statementCount] = statementNode;
stackFrame->statementCount += 1;
}
Node** GetStatements(Stack *stack, uint32_t *pCount)
{
*pCount = stack->stackFrames[stack->stackIndex].statementCount;
return stack->stackFrames[stack->stackIndex].statements;
}
void AddDeclaration(Stack *stack, Node *declarationNode)
{
StackFrame *stackFrame = &stack->stackFrames[stack->stackIndex];
if (stackFrame->declarationCount == stackFrame->declarationCapacity)
{
stackFrame->declarationCapacity += 1;
stackFrame->declarations = (Node**) realloc(stackFrame->declarations, stackFrame->declarationCapacity);
}
stackFrame->declarations[stackFrame->declarationCount] = declarationNode;
stackFrame->declarationCount += 1;
}
Node** GetDeclarations(Stack *stack, uint32_t *pCount)
{
*pCount = stack->stackFrames[stack->stackIndex].declarationCount;
return stack->stackFrames[stack->stackIndex].declarations;
}