词法分析器(c语言实现)(共5页).doc
精选优质文档-倾情为你奉上 词法分析c实现一、 实验目的设计、编制并调试一个词法分析程序,加深对词法分析原理的理解。二、 实验要求2.1 待分析的简单的词法(1)关键字: begin if then while do end所有的关键字都是小写。(2)运算符和界符: = + - * / < <= <> > >= = ; ( ) #(3)其他单词是标识符(ID)和整型常数(SUM),通过以下正规式定义:ID = letter (letter | digit)*NUM = digit digit*(4)空格有空白、制表符和换行符组成。空格一般用来分隔ID、SUM、运算符、界符和关键字,词法分析阶段通常被忽略。2.2 各种单词符号对应的种别码:表2.1 各种单词符号对应的种别码单词符号种别码 单词符号种别码bgin1:17If2:=18Then3<20wile4<>21do5<=22end6>23lettet(letter|digit)*10>=24dight dight*11=25+13;2614(27*15)28/16#02.3 词法分析程序的功能:输入:所给文法的源程序字符串。输出:二元组(syn,token或sum)构成的序列。其中:syn为单词种别码; token为存放的单词自身字符串; sum为整型常数。例如:对源程序begin x:=9: if x>9 then x:=2*x+1/3; end #的源文件,经过词法分析后输出如下序列:(1,begin)(10,x)(18,:=)(11,9)(26,;)(2,if)三、词法分析程序的C语言程序源代码:#include <stdio.h>#include <string.h>char prog80,token8,ch;int syn,p,m,n,sum;char *rwtab6="begin","if","then","while","do","end" scaner();main()p=0; printf("n please input a string(end with '#'):/n"); do scanf("%c",&ch); progp+=ch; while(ch!='#'); p=0; do scaner(); switch(syn) case 11:printf("( %-10d%5d )n",sum,syn); break; case -1:printf("you have input a wrong stringn"); getch(); exit(0); default: printf("( %-10s%5d )n",token,syn); break; while(syn!=0); getch(); scaner() sum=0; for(m=0;m<8;m+)tokenm+=NULL; ch=progp+; m=0; while(ch=' ')|(ch='n')ch=progp+; if(ch<='z')&&(ch>='a')|(ch<='Z')&&(ch>='A') while(ch<='z')&&(ch>='a')|(ch<='Z')&&(ch>='A')|(ch>='0')&&(ch<='9') tokenm+=ch; ch=progp+; p-; syn=10; for(n=0;n<6;n+) if(strcmp(token,rwtabn)=0) syn=n+1; break; else if(ch>='0')&&(ch<='9') while(ch>='0')&&(ch<='9') sum=sum*10+ch-'0' ch=progp+; p-; syn=11; else switch(ch) case '<':tokenm+=ch; ch=progp+; if(ch='=') syn=22; tokenm+=ch; else syn=20; p-; break; case '>':tokenm+=ch; ch=progp+; if(ch='=') syn=24; tokenm+=ch; else syn=23; p-; break; case '+': tokenm+=ch; ch=progp+; if(ch='+') syn=17; tokenm+=ch; else syn=13; p-; break; case '-':tokenm+=ch; ch=progp+; if(ch='-') syn=29; tokenm+=ch; else syn=14; p-; break; case '!':ch=progp+; if(ch='=') syn=21; tokenm+=ch; else syn=31; p-; break; case '=':tokenm+=ch; ch=progp+; if(ch='=') syn=25; tokenm+=ch; else syn=18; p-; break; case '*': syn=15; tokenm+=ch; break; case '/': syn=16; tokenm+=ch; break; case '(': syn=27; tokenm+=ch; break; case ')': syn=28; tokenm+=ch; break; case '': syn=5; tokenm+=ch; break; case '': syn=6; tokenm+=ch; break; case '': syn=26; tokenm+=ch; break; case '"': syn=30; tokenm+=ch; break; case '#': syn=0; tokenm+=ch; break; case ':':syn=17; tokenm+=ch; break; default: syn=-1; break; tokenm+='0' 四、结果分析:输入begin x:=9: if x>9 then x:=2*x+1/3; end # 后经词法分析输出如下序列:(begin 1)(x 10)(:17)(= 18)(9 11)(;26)(if 2) 如图5-1所示:专心-专注-专业