%{ /* define constants for C program here */ #include #include enum { LT, LE, EQ, NE, GT, GE }; enum { IF = 1, THEN, ELSE, RELOP, ID, NUM }; struct token { int type; double value; } yylval; /* declare symbol table management functions. */ void set_default_type(); int init_symtbl(); int install_id(); int gettoken(); char* get_id(); %} /* regular definitions */ delim [ \t\n] ws {delim}+ letter [A-Za-z] digit [0-9] id {letter}({letter}|{digit})* number {digit}+(\.{digit}+)?(E[+\-]?{digit}+)? %% {ws} {/* no action and no return */} {id} {yylval.type = gettoken(yytext); yylval.value = install_id(yytext); return(yylval.type);} {number} {yylval.value = atof(yytext); return(NUM);} "<" {yylval.value = LT; return(RELOP);} "<=" {yylval.value = LE; return(RELOP);} "=" {yylval.value = EQ; return(RELOP);} "<>" {yylval.value = NE; return(RELOP);} ">" {yylval.value = GT; return(RELOP);} ">=" {yylval.value = GE; return(RELOP);} %% #include "symtable.c" main() { int token; set_default_type(ID); init_symtbl(IF, "if"); init_symtbl(THEN, "then"); init_symtbl(ELSE, "else"); while(token=yylex()) { printf("TOKEN "); switch(token) { case ID: printf("ID, lexeme = %s\n", get_id((int)yylval.value)); break; case NUM: printf("NUM, value = %f\n", yylval.value); break; case RELOP: printf("RELOP, symbol = %d\n", (int)yylval.value); break; default: printf("KEYWORD, type=%d\n", yylval.type); } } }