86 lines
1.9 KiB
C
86 lines
1.9 KiB
C
#include "../includes/token.h"
|
|
|
|
#define LISTDEFAULTSIZE 32
|
|
|
|
Token* CreateToken(int lineNumber, TokenClass tokenClass) {
|
|
Token* token = calloc(1, sizeof(Token));
|
|
|
|
if (!token) {
|
|
fprintf(stderr, "Failed to calloc memory for Token. %s.\n", strerror(errno));
|
|
return NULL;
|
|
}
|
|
|
|
token->Class = tokenClass;
|
|
token->LineNumber = lineNumber;
|
|
|
|
return token;
|
|
}
|
|
|
|
void FreeToken(Token* token) {
|
|
if (!token) return;
|
|
|
|
free(token);
|
|
}
|
|
|
|
TokenList* CreateTokenList(void) {
|
|
TokenList *new = malloc(sizeof(TokenList));
|
|
|
|
if (!new) {
|
|
fprintf(stderr, "Failed to malloc() for new new List.\n");
|
|
return NULL;
|
|
}
|
|
|
|
new->content = calloc(LISTDEFAULTSIZE, sizeof(void*));
|
|
|
|
if (!new->content) {
|
|
fprintf(stderr, "Failed to malloc() memory for List contents.\n");
|
|
free(new);
|
|
return NULL;
|
|
}
|
|
|
|
new->size = 0;
|
|
new->capacity = LISTDEFAULTSIZE;
|
|
|
|
return new;
|
|
}
|
|
|
|
int AddToken(Token* token, TokenList* list) {
|
|
if (!list || !token) return 0;
|
|
|
|
if (list->capacity < list->size + 1) {
|
|
void* ptr = realloc(list->content, sizeof(void*) * list->capacity * 2);
|
|
//Note: realloc will free list->root if it succeeds.
|
|
if (!ptr) {
|
|
fprintf(stderr, "Failed to resize array with realloc() (%d bytes).\n", list->capacity * 2);
|
|
return 0;
|
|
}
|
|
|
|
list->content = ptr;
|
|
list->capacity *= 2;
|
|
}
|
|
|
|
if (list->size > 0)
|
|
{
|
|
Token* prev = list->content[list->size - 1];
|
|
|
|
token->Prev = prev;
|
|
prev->Next = token;
|
|
}
|
|
|
|
list->content[list->size] = token;
|
|
list->size++;
|
|
|
|
return 1;
|
|
}
|
|
|
|
void RemoveToken(int index, TokenList* list) {
|
|
Token* token = list->content[index];
|
|
|
|
if (token->Prev) token->Prev->Next = token->Next;
|
|
|
|
memmove(&list->content[index], &list->content[index + 1], (list->size - index) * sizeof(Token*));
|
|
|
|
list->size--;
|
|
|
|
list->content[list->size] = NULL;
|
|
} |