apfl/src/token.c

123 lines
2.6 KiB
C
Raw Normal View History

2021-12-10 20:22:16 +00:00
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "apfl.h"
static bool
has_text_data(enum apfl_token_type type)
{
switch (type) {
case APFL_TOK_NAME:
case APFL_TOK_STRING:
case APFL_TOK_COMMENT:
return true;
default:
return false;
}
}
static bool
has_numeric_data(enum apfl_token_type type)
{
switch (type) {
case APFL_TOK_NUMBER:
return true;
default:
return false;
}
}
void
apfl_token_deinit(struct apfl_token *token)
{
if (has_text_data(token->type)) {
apfl_string_deinit(&token->text);
}
}
const char *
apfl_token_type_name(enum apfl_token_type type)
{
switch (type) {
case APFL_TOK_LPAREN:
return "(";
case APFL_TOK_RPAREN:
return ")";
case APFL_TOK_LBRACKET:
return "[";
case APFL_TOK_RBRACKET:
return "]";
case APFL_TOK_LBRACE:
return "{";
case APFL_TOK_RBRACE:
return "}";
case APFL_TOK_MAPSTO:
return "->";
case APFL_TOK_EXPAND:
return "~";
case APFL_TOK_DOT:
return ".";
case APFL_TOK_AT:
return "@";
case APFL_TOK_SEMICOLON:
return ";";
case APFL_TOK_LINEBREAK:
return "LINEBREAK";
case APFL_TOK_CONTINUE_LINE:
return "\\";
case APFL_TOK_COMMENT:
return "COMMENT";
case APFL_TOK_COMMA:
return ",";
case APFL_TOK_QUESTION_MARK:
return "?";
case APFL_TOK_STRINGIFY:
return "'";
case APFL_TOK_ASSIGN:
return "=";
case APFL_TOK_LOCAL_ASSIGN:
return ":=";
case APFL_TOK_NUMBER:
return "NUMBER";
case APFL_TOK_NAME:
return "NAME";
case APFL_TOK_STRING:
return "STRING";
}
return "(unknown token)";
}
void
apfl_token_print(struct apfl_token token, FILE *file)
{
if (has_text_data(token.type)) {
fprintf(
file,
"%s (" APFL_STR_FMT ") @ (%d:%d)\n",
apfl_token_type_name(token.type),
APFL_STR_FMT_ARGS(token.text),
token.position.line,
token.position.col
);
} else if (has_numeric_data(token.type)) {
fprintf(
file,
"%s (%f) @ (%d:%d)\n",
apfl_token_type_name(token.type),
token.number,
token.position.line,
token.position.col
);
} else {
fprintf(
file,
"%s @ (%d:%d)\n",
apfl_token_type_name(token.type),
token.position.line,
token.position.col
);
}
}