Files
clox/token.c
T

93 lines
2.5 KiB
C

#include "token.h"
#include <stdlib.h>
#include <string.h>
KeyValuePair TokenTypeMappings[TOKENTYPE_MAPPINGS_COUNT] = {
{ "(", LParen}, { ")", RParen}, { ",", Comma }, { ".", Dot },
{ "-", Minus }, { "+", Plus }, { ";", Semicolon }, { "/", Slash}, { "*", Star },
{ "!", Bang }, { "!=", Bang_Equal }, { "=", Equal }, { "==", Equal_Equal },
{ ">", Greater }, { ">=", Greater_Equal }, { "<", Less }, { "<=", Less_Equal },
{ "and", AND }, { "class", CLASS }, { "else", ELSE },
{ "false", FALSE }, { "for", FOR }, { "fun", FUN },
{ "if", IF }, { "nil", NIL }, { "or", OR },
{ "print", PRINT }, { "return", RETURN }, { "super", SUPER },
{ "this", THIS }, { "true", TRUE }, { "var", VAR }, { "while", WHILE },
{ "", EndOF }
};
const char* GetLexemeMapping(TokenType);
Token* CreateToken(const char* lexeme, void* literal, int line, TokenType type) {
Token* token = calloc(1, sizeof(Token));
if (!token) {
fprintf(stderr, "Failed to calloc token. %s", strerror(errno));
return NULL;
}
if (lexeme) {
token->literal = literal;
token->lexeme = lexeme;
}
else {
const char* mapping_result = GetLexemeMapping(type);
if (!mapping_result) {
fprintf(stderr, "Failed to get the mapping for %s\n", lexeme);
free(token);
return NULL;
}
if (type != NIL) token->literal = mapping_result;
token->lexeme = mapping_result;
}
token->line = line;
token->type = type;
return token;
}
const char* GetLexemeMapping(TokenType type) {
for (int i = 0; i < TOKENTYPE_MAPPINGS_COUNT; i++) {
if (TokenTypeMappings[i].type == type) return TokenTypeMappings[i].lexeme;
}
return NULL;
}
void FreeToken(Token* token) {
if (!token) return;
if (token->type == String || token->type == Number || token->type == Identifier) free((void *) token->lexeme);
free(token);
}
char* GetTokenStringValue(Token* token, int* length) {
length = 0;
if (!token) return NULL;
if (token->type != String) return NULL;
*length = strlen(token->lexeme);
if (length == 0) return NULL;
char* value = calloc(strlen(token->lexeme) + 1, sizeof(char));
strncpy(value, token->lexeme, *length);
return value;
}
int GetTokenNumberValue(Token* token, double* value) {
value = 0;
if (!token) return 0;
if (token->type != Number) return 0;
*value = *((double*)token->literal);
return 1;
}