%{ #include /* #define token(x) x */ #define EndTable(v) (v-1 + sizeof v/sizeof v[0]) int screen(); int addword(int type, char *word); int lookup_word(char *word); #define constant 1 #define identifier 2 #define NOTFOUND -1 %} %% ":=" { printf("%s: ASSIGN", yytext); return(7);} ":" { printf("%s: COLON", yytext); return(8);} "," { printf("%s: COMMA", yytext); return(9);} "." { printf("%s: DOT", yytext); return(10);} "=" { printf("%s: EQUAL", yytext); return(11);} "*" { printf("%s: MULT", yytext); return(12);} "+" { printf("%s: PLUS", yytext); return(13);} ";" { printf("%s: SEMICOL", yytext); return(14);} [\t\n]+ { printf("%s: WhiteSpace", yytext); } [ ]+ { printf("%s: WhiteSpace", yytext); } [0-9][0-9]* {printf("%s: const", yytext); addword(constant, yytext); return(15);} [a-zA-Z_][a-zA-Z0-9]* { return screen();} %% main(){ char *p; while(p= (char *)yylex()) ; printf("\nsuccessful scanning.\n"); } static struct rwtable{ char *rw_name; int rw_yylex; } rwtable[] = { "BEGIN", 1, "CONST", 2, "END", 3, "INTEGER", 4, "PROGRAM", 5, "VAR", 6, }; struct word{ char *word_name; int word_type; /* int value; */ struct word *next; }; struct word *word_list = NULL; int addword(int type, char *word) { struct word *wp; wp = (struct word *) malloc(sizeof(struct word)); wp->next = word_list; wp->word_name = (char *) malloc(strlen(word)+1); strcpy(wp->word_name, word); wp->word_type = type; /* wp->value = ; */ word_list = wp; return 1; } int lookup_word(char *word) { struct word *wp = word_list; for(;wp;wp = wp->next){ if(strcmp(wp->word_name, word) == 0) return(wp->word_type); } return NOTFOUND; } int screen() { struct rwtable *low = rwtable, *high = EndTable(rwtable), *mid; int c; while(low <= high){ mid = low + (high - low)/2; if((c = strcmp(mid->rw_name, yytext)) == 0){ printf("%s: keyword", yytext); return(mid->rw_yylex); } else{ if(c < 0) low = mid + 1; else high = mid - 1; } } if(lookup_word(yytext) != NOTFOUND){ printf("%s: id", yytext); return(16); } else{ addword(identifier, yytext); printf("%s: id", yytext); return(16); } }