2012年(32)
分类: Python/Ruby
2012-03-02 18:19:07
代码下载: git clone git://git.code.sf.net/p/redy/code redy-code这一章的内容有:
关键字的识别
在前面,我们是把关键字和识别与变量的识别结合再一起来,这样做是因为为关键字构造状态机是一件很烦锁的事情,如果要构造一个能成功识别上面关键字的状态机,至少需要100多个状态,无论是编写,绘图,还是维护都是一件费脑力与体力的活,所以,我们也关键字的识别与变量识别结合在一起,当词法识别系统识别到一个变量的词文时,我们再来对判断该词文是否真的是变量,还是关键字。
- 'class' 'attr' 'end' 'inhrit' 'vfunc' 'func'
- 'import' 'as' 'to' 'from'
- 'break' 'continue' 'for' 'while' 'do' 'in'
- 'if' 'elif' 'else' 'then'
- 'return' 'and' 'or' 'not'
- 'print' 'try' 'catch' 'finally
- struct keyword
- {
- char* k_name;
- int k_token;
- };
- struct keyword key_words[]=
- {
- {"and",TOKEN_AND},
- {"as",TOKEN_AS},
- {"attr",TOKEN_ATTR},
- {"break",TOKEN_BREAK},
- {"catch",TOKEN_CATCH},
- {"class",TOKEN_CLASS},
- {"continue",TOKEN_CONTIUNE},
- {"do",TOKEN_DO},
- {"elif",TOKEN_ELIF},
- {"else",TOKEN_ELSE},
- {"end",TOKEN_END},
- {"finally",TOKEN_FINALLY},
- {"for",TOKEN_FOR},
- {"from",TOKEN_FROM},
- {"func",TOKEN_FUNC},
- {"if",TOKEN_IF},
- {"import",TOKEN_IMPORT},
- {"in",TOKEN_IN},
- {"inhrit",TOKEN_INHRIT},
- {"not",TOKEN_NOT},
- {"or",TOKEN_OR},
- {"print",TOKEN_PRINT},
- {"return",TOKEN_RETURN},
- {"then",TOKEN_THEN},
- {"to",TOKEN_TO},
- {"try",TOKEN_TRY},
- {"vfunc",TOKEN_VFUNC},
- {"while",TOKEN_WHILE},
- };
- int symbol_type(char* symbol)
- {
- int begin=0;
- int end=KEYWORD_NUM-1;
- int middle;
- while(begin<=end) /*采用二分查找算法*/
- {
- middle=(begin+end)/2;
- int ret=strcmp(symbol,key_words[middle].k_name);
- printf("cmp %s ,%s =%d\n",key_words[middle].k_name,symbol,ret);
- if(ret<0)
- {
- end=middle-1;
- }
- else if(ret >0)
- {
- begin=middle+1;
- }
- else
- {
- return key_words[middle].k_token;
- }
- }
- return TOKEN_ID;
- }
- int main()
- {
- char buf[1024];
- printf("input __quit__ exit\n");
- printf("input:\n");
- scanf("%s",buf);
- while(strcmp(buf,"__quit__")!=0)
- {
- int token=symbol_type(buf);
- printf("it's %s\n",token_info[token]);
- printf("input:\n");
- scanf("%s",buf);
- }
- return 0;
- }