Initial import of c parser
[cparser] / token.c
1 #include <config.h>
2
3 #include "token_t.h"
4
5 #include <assert.h>
6 #include <stdio.h>
7
8 #include "symbol.h"
9 #include "adt/array.h"
10
11 static symbol_t *token_symbols[T_LAST_TOKEN];
12
13 void init_tokens(void)
14 {
15         symbol_t *symbol;
16
17         memset(token_symbols, 0, T_LAST_TOKEN * sizeof(token_symbols[0]));
18
19 #define T(x,str,val)                                               \
20         assert(T_##x >= 0 && T_##x < T_LAST_TOKEN);                    \
21         symbol               = symbol_table_insert(str);               \
22         symbol->ID           = T_##x;                                  \
23         token_symbols[T_##x] = symbol;
24
25 #define TS(x,str,val)                                              \
26         assert(T_##x >= 0 && T_##x < T_LAST_TOKEN);                    \
27         symbol               = symbol_table_insert(str);               \
28         token_symbols[T_##x] = symbol;
29
30 #include "tokens.inc"
31
32 #undef TS
33 #undef T
34 }
35
36 void exit_tokens(void)
37 {
38 }
39
40 void print_token_type(FILE *f, token_type_t token_type)
41 {
42         if(token_type >= 0 && token_type < 256) {
43                 fprintf(f, "'%c'", token_type);
44                 return;
45         }
46         if(token_type == T_EOF) {
47                 fputs("end of file", f);
48                 return;
49         }
50
51         int token_symbols_len = T_LAST_TOKEN;
52         if(token_type < 0 || token_type >= token_symbols_len) {
53                 fputs("invalid token", f);
54                 return;
55         }
56
57         const symbol_t *symbol = token_symbols[token_type];
58         if(symbol != NULL) {
59                 fputs(symbol->string, f);
60         } else {
61                 fputs("unknown token", f);
62         }
63 }
64
65 void print_token(FILE *f, const token_t *token)
66 {
67         switch(token->type) {
68         case T_IDENTIFIER:
69                 fprintf(f, "symbol '%s'", token->v.symbol->string);
70                 break;
71         case T_INTEGER:
72                 fprintf(f, "integer number %d", token->v.intvalue);
73                 break;
74         case T_STRING_LITERAL:
75                 fprintf(f, "string '%s'", token->v.string);
76                 break;
77         default:
78                 print_token_type(f, token->type);
79                 break;
80         }
81 }