static struct
{
char* str;
int tok;
} reservedWords[3] =
{ {"main",MAIN},
{"if", IF },
};
int getToken(void)
{
int tokenStringIndex = 0;
int currentToken;
StateType state = START;
int save;
static j=0;
while (state != DONE) {
char c = getNextChar();
save = 1;
switch (state) {
case START:
if (isdigit(c))
state = INNUM;
else if (isalpha(c))
state = INID;
else if (c == '=')
state = INEQULE;
else if (c == '>')
state =INMORE;
else if (c == '<')
state =INLESS;
else if (c == '!')
state =INNEQULE;
else if ( (c == ' ') || (c == '\t') || (c == '\n') )
save = 0;
else {
state = DONE;
switch (c) {
case EOF:
save = 0;
currentToken = ENDFILE;
break;
case '+':
currentToken = PLUS;
break;
case '-':
currentToken = MINUS;
break;
case '*':
currentToken = TIMES;
break;
case '/':
currentToken = OVER;
break;
case '(':
currentToken = LPAREN;
break;
case ')':
currentToken = RPAREN;
break;
case ';':
currentToken = SEMI;
break;
case '{':
currentToken = LBRACKET;
break;
case '}':
currentToken = RBRACKET;
break;
default:
currentToken = ERROR;
break;
}
}
break;
case INEQULE:
state = DONE;
if (c == '=')
currentToken = EQ;
else {
ungetNextChar();
save = 0;
currentToken = ASSIGN;
}
break;
case INNEQULE:
state = DONE;
if (c == '=')
currentToken = NE;
else {
ungetNextChar();
save = 0;
currentToken = ERROR;
}
break;
case INMORE:
state = DONE;
if (c == '=')
currentToken = ME;
else {
ungetNextChar();
save = 0;
currentToken = MORE;
}
break;
case INLESS:
state = DONE;
if (c == '=')
currentToken = LE;
else {
ungetNextChar();
save = 0;
currentToken = LESS;
}
break;
case INNUM:
if (!isdigit(c)) {
if(!isalpha(c)){
ungetNextChar();
save = 0;
state = DONE;
currentToken = NUM;
}
else{
save = 1;
state = DONE;
currentToken =ERROR;
}
}
break;
case DONE:
default:
state = DONE;
currentToken = ERROR;
break;
}
if ( (save) && (tokenStringIndex <= MAXTOKENLEN) )
tokenString[tokenStringIndex++] = c;
if ( state == DONE) {
tokenString[tokenStringIndex] = '\0';
if (currentToken == ID)
currentToken = reservedLookup(tokenString);
}
}
if (currentToken!=ERROR) {
if(currentToken){
printf("(%d,%s) ",currentToken,tokenString);
fprintf(fpout,"(%d,%s)",currentToken,tokenString);
if(!(++j%10)) printf("\n");
}
else {
gotoxy(1,24);
printf("Succeed! Result been put into 'out.txt'.");
printf("\nPress any key to continue... ");
getch();
}
}
else {
gotoxy(1,24);
printf("Illegal character '%s' (Row %d,Column %d)",tokenString,lineno,linepos);
printf("\nPress any key to continue... ");
window(linepos,lineno+2,linepos,lineno+2);
textbackground(4);
clrscr();
printf("%c",tokenString[tokenStringIndex-1]);
textbackground(0);
fclose(fpin);
fclose(fpout);
getch();
exit(-1);
}