1
0
Fork 0
lesson-lisp/tokens.c

54 lines
1.1 KiB
C

#include "tokens.h"
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
static struct Tokens *tokens = NULL;
const struct Tokens *tokens_top()
{
return tokens;
}
bool tokens_expect(const enum TokenType token_type)
{
if (!tokens && tokens->type != token_type) return false;
tokens_pop();
return true;
}
void tokens_pop()
{
struct Tokens *const token = tokens;
if (token) {
tokens = token->next;
if (token->val) free(token->val);
free(token);
}
}
void tokens_push(const enum TokenType token_type, const char *const val)
{
struct Tokens *token = malloc(sizeof(struct Tokens));
assert(token);
token->next = NULL;
token->type = token_type;
token->val = malloc(strlen(val) + 1);
assert(token->val);
strcpy(token->val, val);
if (!tokens) {
tokens = token;
} else {
for (struct Tokens *curr = tokens; curr; curr = curr->next) {
if (!curr->next) {
curr->next = token;
break;
}
}
}
}