Compiler now halting on end of input.
[Jack-Compiler.git] / token.c
blobcc8cbb2175f4cda4ed2353439188e542312b67c4
1 #include <ctype.h>
2 #include <stdbool.h>
3 #include <stdlib.h>
4 #include <stdio.h>
5 #include <string.h>
7 #include "token.h"
9 char *keywords[] =
11 "boolean","char", "class", "constructor", "do", "else",
12 "false", "field", "function", "if", "int", "let", "method",
13 "null", "return", "static", "this", "true", "var", "void", "while"
16 int has_more_tokens(char *pC)
18 if(*(pC+1) == '\0')
20 return false;
21 } else {
22 return true;
26 char *advance(char *pC, char pT[])
28 char ch;
29 int cont; /* continue */
30 int in_quote = 0; /* inside quotes? */
31 do {
32 cont = 0;
33 /* skip past C++ style comments */
34 if(*pC == '/' && *(pC+1) == '/')
36 pC = strchr(pC, '\n');
39 /* skip past C style comments */
40 if(*pC == '/' && *(pC+1) == '*')
42 pC++;
43 pC = strchr(pC, '/');
44 pC++;
47 /* advance past spaces and newline chars */
48 ch = *pC;
49 while((strchr(SPACES, ch)) != NULL)
51 pC++;
52 ch = *pC;
55 /* determine if more advancement is needed */
56 if(*pC == '/' && *(pC+1) == '/') { cont++; }
57 if(*pC == '/' && *(pC+1) == '*') { cont++; }
59 } while (cont);
61 /* test for symbol - copy to buffer */
62 ch = *pC;
63 if(strchr(SYMBOLS, ch) != NULL)
65 pT[0] = ch;
66 pT[1] = '\0';
67 pC++;
68 return pC;
71 /* should be at beginning of token - copy to buffer */
72 cont = 0; in_quote = 0;
73 if(*pC == '"')
75 in_quote++; /* inside quote */
76 pC++; /* skip quote itself */
78 while(TRUE)
80 if(in_quote){
81 if(*pC == '"') { pC++; break; } /* found corresponding quote, stop */
82 } else {
83 if(((strchr(SPACES, ch)) != NULL) || ((strchr(SYMBOLS, ch)) != NULL))
85 break;
88 pT[cont] = *pC;
89 pC++;
90 ch = *pC;
91 cont++;
93 pT[cont] = '\0';
94 return pC;
98 token token_type(char pT[])
100 token t = IDENTIFIER;
101 int i = 0, j = 0;;
103 /* check token for symbols */
104 if(strchr(SYMBOLS, pT[0]) != NULL) { t = SYMBOL; }
106 /* check token for integer constants */
107 while(pT[i] != '\0')
109 if(isdigit(pT[i]) == 0)
111 j++;
112 break;
114 i++;
116 if(j == 0) { t = INT_CONST; }
118 /* check token for keywords */
119 i = 0; j = 0;
120 do {
121 j = strcmp(keywords[i], pT);
122 i++;
123 } while ((j != 0) && (i < KEYWORD_COUNT));
125 if(j == 0) { t = KEYWORD; }
126 return t;
130 ttype keyword(char pT[])
132 int i = 0;
133 do {
134 i++;
135 } while (strcmp(pT, keywords[i]) < 0 && i < KEYWORD_COUNT);
136 return i;
140 char symbol()
142 return 'z';
146 char *identifier(char *str)
148 str = NULL;
149 return NULL;
153 int int_val(char pT[])
155 return atoi(pT);
159 char *string_val()
161 return NULL;