lex与yacc之lex符号表示例

在lex初探篇中,每次要定义新的单词,都需要重新编译,这是非常麻烦的。但是如果在词法分析程序运行时能够构建一个单词表,那么就可以在
添加新的单词时不用修改和重新编译lex程序。

symboltable.l
%{ /* * Word recognizer with a symbol table. */ enum { LOOKUP = 0, VERB, ADJ, ADV, NOUN, PREP, PRON, CONJ }; int state; int AddWord(int type,char* word); int LookupWord(char* word); %} %% /n {state = LOOKUP;} ^verb {state = VERB;} ^adj {state = ADJ;} ^adv {state = ADV;} ^noun {state = NOUN;} ^prep {state = PREP;} ^pron {state = PRON;} ^conj {state = CONJ;} [a-zA-Z]+ { if(state!=LOOKUP) { AddWord(state,yytext); } else { switch(LookUpWord(yytext)) { case VERB: printf("%s: verb/n",yytext); break; case ADJ: printf("%s: adjective/n",yytext); break; case ADV: printf("%s: adverb/n",yytext); break; case NOUN: printf("%s: noun/n",yytext); break; case PREP: printf("%s: preposition/n",yytext); break; case PRON: printf("%s: pronoun/n",yytext); break; case CONJ: printf("%s: conjunction/n",yytext); break; default: printf("%s: don't recognize/n",yytext); break; } } } . /* ignore anything else */; %% main() { yylex(); } struct word { char* wordName; int wordType; struct word* next; }; struct word *wordList = 0; extern void* malloc(); int AddWord(int type,char* word) { struct word* wp; if(LookUpWord(word)!=LOOKUP) { printf("!!! warning: word %s already defined /n",word); return 0; } wp = (struct word*) malloc(sizeof(struct word)); wp->next = wordList; wp->wordName = (char*) malloc(strlen(word)+1); strcpy(wp->wordName,word); wp->wordType = type; wordList = wp; return 1; } int LookUpWord(char* word) { struct word* wp = wordList; for(;wp;wp=wp->next) { if(strcmp(wp->wordName,word)==0) return wp->wordType; } return LOOKUP; } int yywrap() { return 1; }
用cygwin生成编译:
flex symboltable.l
gcc -o symboltable lex.yy.c

执行
$ ./symboltable
verb is am are was were be being been do
is
is: verb
asdasdasd
asdasdasd: don't recognize
noun dog cat horse cow
verb chew eat lock

你可能感兴趣的:(Linux,yacc,struct,flex)