diff options
-rw-r--r-- | Token.c | 13 | ||||
-rw-r--r-- | Token.h | 2 | ||||
-rw-r--r-- | lexer.c | 21 | ||||
-rw-r--r-- | main.c | 6 | ||||
-rw-r--r-- | parse.c | 5 |
5 files changed, 24 insertions, 23 deletions
@@ -4,21 +4,16 @@ void token_free(Token *tok) { - switch (tok->type) { - case TOK_WORD: - if (tok != NULL && tok->v.s != NULL) - free(tok->v.s); - default: - break; - } + if (tok != NULL && tok->s != NULL) + free(tok->s); } void token_print(const Token *tok) { printf("%u:%u\t", tok->line, tok->column); switch (tok->type) { - case TOK_WORD: printf("TOK_WORD %s\n", tok->v.s); break; - case TOK_STRING: printf("TOK_STRING \"%s\"\n", tok->v.s); break; + case TOK_WORD: printf("TOK_WORD %s\n", tok->s); break; + case TOK_STRING: printf("TOK_STRING \"%s\"\n", tok->s); break; case TOK_INTEGER: printf("TOK_INTEGER %d\n", tok->v.i); break; case TOK_PAREN_OPEN: printf("TOK_PAREN_OPEN\n"); break; case TOK_PAREN_CLOS: printf("TOK_PAREN_CLOS\n"); break; @@ -31,7 +31,6 @@ enum { }; union TokenValue { - char *s; char c; int i; double d; @@ -43,6 +42,7 @@ typedef struct Token { unsigned int line; unsigned int column; union TokenValue v; + char *s; } Token; void token_free(Token *tok); @@ -81,28 +81,35 @@ Token *lexer(const char *s) return NULL; } size_t len = end - s - 1; - toks[tok_i].v.s = calloc(1, len + 1); - if (toks[tok_i].v.s == NULL) { + toks[tok_i].s = calloc(1, len + 1); + if (toks[tok_i].s == NULL) { perror("lexer"); lexer_free(toks); return NULL; } toks[tok_i].type = TOK_STRING; - strncpy(toks[tok_i].v.s, s + 1, len); + strncpy(toks[tok_i].s, s + 1, len); tok_i += 1; s = end + 1; } else if (isalpha(*s) || *s == '_') { size_t len = 0; while (isalnum(s[len]) || s[len] == '_') len += 1; - toks[tok_i].v.s = calloc(1, len + 1); - if (toks[tok_i].v.s == NULL) { + toks[tok_i].s = calloc(1, len + 1); + if (toks[tok_i].s == NULL) { perror("lexer"); lexer_free(toks); return NULL; } - strncpy(toks[tok_i].v.s, s, len); - toks[tok_i].type = TOK_WORD; + strncpy(toks[tok_i].s, s, len); + if (strcmp("fn", toks[tok_i].s) == 0) + toks[tok_i].type = TOK_KW_FN; + else if (strcmp("var", toks[tok_i].s) == 0) + toks[tok_i].type = TOK_KW_VAR; + else if (strcmp("const", toks[tok_i].s) == 0) + toks[tok_i].type = TOK_KW_CONST; + else + toks[tok_i].type = TOK_WORD; tok_i += 1; s += len; } else if (isdigit(*s)) { @@ -28,11 +28,7 @@ int main(int argc, char **argv) fprintf(stderr, "lexer failed\n"); return 1; } - lexer_print(toks); - if (parse(toks)) { - fprintf(stderr, "parser failed\n"); - return 1; - } + parse(toks); lexer_free(toks); return 0; } @@ -10,8 +10,11 @@ int parse(const Token *tok) case TOK_KW_CONST: break; default: - fprintf(stderr, "unexpected %s at %u:%u\n", + fprintf(stderr, "unexpected %s %s%s%sat %u:%u\n", token_type_str(tok->type), + (tok->s != NULL) ? "(" : "", + (tok->s != NULL) ? tok->s : "", + (tok->s != NULL) ? ") " : "", tok->line, tok->column); return 1; } |