使用flex对tiny语言进行词法分析
发布时间:2020-12-15 04:45:58 所属栏目:百科 来源:网络整理
导读:flex的使用方法在这里就不一一说明了,网上很多,这次是编译原理的第一个作业,因为最近学得东西比较多,所以偷懒使用flex进行词法分析。 下面是tiny语言代码 { sample progarm in tiny language - computer factorial}read x;{ input an integer }if x 0 th
flex的使用方法在这里就不一一说明了,网上很多,这次是编译原理的第一个作业,因为最近学得东西比较多,所以偷懒使用flex进行词法分析。 下面是tiny语言代码 { sample progarm in tiny language - computer factorial } read x;{ input an integer } if x < 0 then { don't compute if x <= 0} fact := 1; repeat fact := fact * x; x := x - 1 until x = 0; write fact {output factorial of x} end 就是要使用flex来对上面这段代码进行词法分析,分出哪些是关键字 哪些是运算符等等 首先需要些的是.l文件,这个是flex进行操作的文件 在其中最重要的两个部分 一个就是正则表达式的书写,一个就是识别出来后的操作 下面是demo.l文件的代码 %{ #include "stdio.h" int lineNum; %} digit [0-9]+ keyword read|if|then|repeat|until|write|end letter [a-zA-Z]+ comment {[^}]*} operator ":="|"="|"+"|"-"|"*"|"/"|">"|"<" ignore [","|";"|" "|t|n]+ %% {comment} { printf("%s : commentn",yytext); } {digit} { printf("%s : digitn",yytext); } {keyword} { printf("%s : keywordn",yytext); } {letter} { printf("%s : lettern",yytext); } {operator} { printf("%s : operatorn",yytext); } {ignore} { /*nothing*/ } %% int yywrap() { return 1; } void main() { lineNum = 0; yylex(); return 0; } 都是比较简单的正则表达式 接下来只需要用 flex demo.l命令 即可将demo.l文件编译成一个c文件,然后将这个c文件编译运行后,即可得到一个exe文件,就用这个文件来解析tiny语言,下面是解析结果截图 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |