词法分析之实验报告

 词法分析实验

一、实验目的

       编制一个词法分析程序

二、实验内容和要求

     1.输入:源程序字符串

     2.输出:二元组(种别,单词本身)

单词与种别码

三、实验方法、步骤及结果测试

    (一).原理分析及流程图

      1.原理分析   

         存储结构:此词法分析程序,我采用的主要存储结构有链队列和指针数组。链队列用于存        储输入的原程序,之所以考虑用链队列,是因为链队列是需要时才申请空间的,更重要的原因      是链队列是先进先出的,这符合我要编写的词法分析程序,而数组是在定义时就要设置好它的      容量,系统会为其分配一个固定容量的存储空间,数组一旦创建后,它的容量就不能更改,所      以它很容易造成数组越界而导致程序终止,数组容量过大就会浪费存储空间,会影响程序的运      行速度。此程序指针数组是用于存储关键字、符、算符、界符等已知其需要多大存储空间的字      符,而且程序上涉及的种别码可以通过获取数组下标得到。

         主要算法:先将源程序用链队列存储起来,然后逐一从链队列中取出单个字符分析,具体         实 现,看下面的流程图

     关键函数的实现:

      void InitQueue()      //初始化一个带节点的空队列

      void Printf()         //输出原程序

      int search(char searchstr[],int wordtype)//符号匹配 返回种别码

      void Analyze()   //词法程序分析

   2.流程图

 

2.主要程序段及其解释:

 1 void Analyze()
 2 {
 3     char str;
 4     char letter[20];         //存放字母的数组
 5     char num[20];          //存放数字的字符数组
 6     char other[20];          //存放其他字符的数组
 7     int i;                  
 8     do                     //循环获取字符分析
 9     {
10         Q.front=Q.front->next;        //获取单个字符 
11         str=Q.front->ch;              //出队列
12         if (isalpha(str)!=0)        //如果是字符 
13         {
14             i=-1;
15            while (isalnum(str)!=0)         //判断下一个字符是否是字母
16           {  
17             letter[++i]=str;                //将字母存放到字符数组
18             Q.front=Q.front->next;          //出队列
19             str=Q.front->ch;               //获取下一个字符
20           }  
21            letter[i+1]='\0';                 //字符串的结束
22            if (search(letter,1)!=-1) // 调用int search(char searchstr[],int wordtype)函数,判断该字符串是否能和指针数组中的字符串匹配
23           {  
24             printf("( %d,%s )\n",search(letter,1),letter);//输出种别码和单词本身
25             
26           }  
27           else  
28           {  
29               printf("( %d,%s )\n",71,letter);        //输出种别码和单词本身
30            }  
31         }    
32         else  
33         {  
34             if (isdigit(str)!=0)      //判断是否为数字
35             {
36                 i=-1;
37                 while (isdigit(str)!=0)  //判断下一个字符是否为数字
38                 {  
39                    num[++i]=str;    //将数字存放到数字字符数组里去
40                    Q.front=Q.front->next;    //出队列
41                    str=Q.front->ch;    //获取下一个字符
42                 }  
43                 if(isalpha(str)!=0)         //数字后面是字符   
44                 {  
45                     while(isspace(str)==0)  
46                    {  
47                      num[++i]=str; 
48                      Q.front=Q.front->next;   //出队列
49                      str=Q.front->ch;         //获取下一个字符
50 
51                     }  
52                    num[i+1]='\0';     //字符串的结束
53                    printf("错误!非法标识符:%s\n",num);  
54                 
55                 }  
56                 num[i+1]='\0';  
57                 printf("( %d,%s )\n",72,num);      
58             }
59             else  
60             {
61               i=-1;    
62               if (isspace(str)!=0)     //判断是否为空格
63               {  
64                  Q.front=Q.front->next;   //出队列,即跳过空格
65                  str=Q.front->ch;        //获取下一个字符
66                  
67               }  
68               while ((isspace(str)==0)&&(isalnum(str)==0))    
69               {  
70                   other[++i]=str;  
71                   Q.front=Q.front->next;
72                  str=Q.front->ch; 
73                 
74                  
75                }  
76                   other[i+1]='\0';  
77               if (search(other,2)!=-1)  
78                   printf("( %d,%s )\n",search(other,2),other);     //输出种别码和单词本身
79               else if (search(other,3)!=-1)  
80                   printf("( %d,%s )\n",search(other,3),other);  //输出种别码和单词本身
81               else if (search(other,4)!=-1)  
82                   printf("( %d,%s )\n",search(other,4),other);  //输出种别码和单词本身
83               else if (search(other,5)!=-1)  
84                   printf("( %d,%s )\n",search(other,5),other);  //输出种别码和单词本身
85               else if (search(other,6)!=-1)  
86                   printf("( %s,注释符号 )\n",other);  //输出种别码和单词本身
87               else if (search(other,7)!=-1)  
88                   printf("( %d,%s )\n",search(other,7),other);  //输出种别码和单词本身
89               else   
90                   printf("错误!非法字符:%s\n",other);  
91             }
92         }  
93     }while(Q.front!=Q.rear);  
94      printf("词法分析结束,谢谢使用!\n"); 
95 }

3.  运行结果及分析

四、 实验总结

      难点一:. 想将字符串存进数组中去,觉得这样获取种别码比较简单,但是用没有加指针的数组会报错

      解决方法:用一个指针数组存储就可以解决这一问题。

 

      难点二:如果将所有的字符和数字都存储在同一指针数组,那样指针数组看起来太长,且分析时也比较浪费时间,每次都要从头开始匹配

       解决方法:按类型将字符串和字符分别放在不同的指针数组中,获取种别码时要加上前一个数组的长度。

 

      难点三:.输入原程序后,对原程序的分析时,要判断各种字符和数字,判断条件太多,代码长且难看懂,很容易把自己绕晕。

      解决方法:调用#include<ctype.h>库函数里的字符类型判断的函数,这样可以使代码简洁易懂。

 

             

转载于:https://www.cnblogs.com/crx234/p/5957998.html

设计思想 (1)程序主体结构部分: 说明部分 %% 规则部分 %% 辅助程序部分 (2)主体结构的说明 在这里说明部分告诉我们使用的LETTER,DIGIT, IDENT(标识符,通常定义为字母开头的字母数字串)和STR(字符串常量,通常定义为双引号括起来的一串字符)是什么意思.这部分也可以包含一些初始化代码.例如用#include来使用标准的头文件和前向说明(forward ,references).这些代码应该再标记"%{"和"%}"之间;规则部分>可以包括任何你想用来分析的代码;我们这里包括了忽略所有注释中字符的功能,传送ID名称和字符串常量内容到主调函数和main函数的功能. (3)实现原理 程序中先判断这个句语句中每个单元为关键字、常数、运算符、界符,对与不同的单词符号给出不同编码形式的编码,用以区分之。 PL/0语言的EBNF表示 <常量定义>::=<标识符>=<无符号整数>; <标识符>::=<字母>={<字母>|<数字>}; <加法运算符>::=+|- <乘法运算符>::=*|/ <关系运算符>::==|#|<|<=|>|>= <字母>::=a|b|…|X|Y|Z <数字>::=0|1|2|…|8|9 三:设计过程 1. 关键字:void,main,if,then,break,int,Char,float,include,for,while,printfscanf 并为小写。 2."+”;”-”;”*”;”/”;”:=“;”:”;”<“;”<=“;”>“;”>=“;”<>“;”=“;”(“;”)”;”;”;”#”为运算符。 3. 其他标记 如字符串,表示以字母开头的标识符。 4. 空格符跳过。 5. 各符号对应种别码 关键字分别对应1-13 运算符分别对应401-418,501-513。 字符串对应100 常量对应200 结束符# 四:举例说明 目标:实现对常量的判别 代码: digit [0-9] letter [A-Za-z] other_char [!-@\[-~] id ({letter}|[_])({letter}|{digit}|[_])* string {({letter}|{digit}|{other_char})+} int_num {digit}+ %% [ |\t|\n]+ "auto"|"double"|"int"|"struct"|"break"|"else"|"long"|"switch"|"case"|"enum"|"register"|"typedef"|"char"|"extern"|"return"|"union"|"const"|"float"|"short"|"unsigned"|"continue"|"for"|"signed"|"void"|"default"|"goto"|"sizeof"|"do"|"if"|"static"|"while"|"main" {Upper(yytext,yyleng);printf("%s,NULL\n",yytext);} \"([!-~])*\" {printf("CONST_string,%s\n",yytext);} -?{int_num}[.]{int_num}?([E][+|-]?{int_num})? {printf("CONST_real,%s\n",yytext);} "0x"?{int_num} {printf("CONST_int,%s\n",yytext);} ","|";"|"("|")"|"{"|"}"|"["|"]"|"->"|"."|"!"|"~"|"++"|"--"|"*"|"&"|"sizeof"|"/"|"%"|"+"|"-"|">"|"<"|">="|"<="|"=="|"!="|"&"|"^"|"|"|"&"|"||"|"+="|"-="|"*="|"/="|"%="|">>="|"<<="|"&="|"^="|"|="|"=" {printf("%s,NULL\n",yytext);} {id} {printf("ID,%s\n",yytext);} {digit}({letter})+ {printf("error1:%s\n",yytext);} %% #include <ctype.h> Upper(char *s,int l) { int i; for(i=0;i<l;i++) { s[i]=toupper(s[i]); } } yywrap() { return 1; } 五:DFA 六:数据测试 七:心得体会 其实匹配并不困难,主要是C++知识要求相对较高,只要把握住指针就好了。 附源程序: #include<iostream.h> #include<stdio.h> #include<stdlib.h> #include<string.h> int i,j,k,flag,number,status; /*status which is use to judge the string is keywords or not!*/ char ch; char words[10] = {" "}; char program[500]; int Scan(char program[]) { char *keywords[13] = {"void","main","if","then","break","int", "char","float","include","for","while","printf", "scanf"}; number = 0; status = 0; j = 0; ch = program[i++]; /* To handle the lettle space ands tab*/ /*handle letters*/ if ((ch >= 'a') && (ch <= 'z' )) { while ((ch >= 'a') && (ch <= 'z' )) { words[j++]=ch; ch=program[i++]; } i--; words[j++] = '\0'; for (k = 0; k < 13; k++) if (strcmp (words,keywords[k]) == 0) switch(k) { case 0:{ flag = 1; status = 1; break; } case 1:{ flag = 2; status = 1; break; } case 2:{ flag = 3; status = 1; break; } case 3:{ flag = 4; status = 1; break; } case 4:{ flag = 5; status = 1; break; } case 5:{ flag = 6; status = 1; break; } case 6:{ flag = 7; status = 1; break; } case 7:{ flag = 8; status = 1; break; } case 8:{ flag = 9; status = 1; break; } case 9:{ flag = 10; status = 1; break; } case 10:{ flag = 11; status = 1; break; } case 11:{ flag = 12; status = 1; break; } case 12:{ flag = 13; status = 1; break; } } if (status == 0) { flag = 100; } } /*handle digits*/ else if ((ch >= '0') && (ch <= '9')) { number = 0; while ((ch >= '0' ) && (ch <= '9' )) { number = number*10+(ch-'0'); ch = program[i++]; } flag = 200; i--; } /*opereation and edge handle*/ else switch (ch) { case '=':{ if (ch == '=') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 401; } else { i--; flag = 402; } break; } case'>':{ if (ch == '>') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 403; } else { i--; flag = 404; } break; } case'<':{ if (ch == '<') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 405; } else { i--; flag = 406; } break; } case'!':{ if (ch == '!') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 407; } else { i--; flag = 408; } break; } case'+':{ if (ch == '+') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 409; } else if (ch == '+') { words[j++] = ch; words[j] = '\0'; flag = 410; } else { i--; flag = 411; } break; } case'-':{ if (ch == '-') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 412; } else if( ch == '-') { words[j++] = ch; words[j] = '\0'; flag = 413; } else { i--; flag = 414; } break; } case'*':{ if (ch == '*') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 415; } else { i--; flag = 416; } break; } case'/':{ if (ch == '/') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 417; } else { i--; flag = 418; } break; } case';':{ words[j] = ch; words[j+1] = '\0'; flag = 501; break; } case'(':{ words[j] = ch; words[j+1] = '\0'; flag = 502; break; } case')':{ words[j] = ch; words[j+1] = '\0'; flag = 503; break; } case'[':{ words[j] = ch; words[j+1] = '\0'; flag = 504; break; } case']':{ words[j] = ch; words[j+1] = '\0'; flag = 505; break; } case'{':{ words[j] = ch; words[j+1] = '\0'; flag = 506; break; } case'}':{ words[j] = ch; words[j+1] = '\0'; flag = 507; break; } case':':{ words[j] = ch; words[j+1] = '\0'; flag = 508; break; } case'"':{ words[j] = ch; words[j+1] = '\0'; flag = 509; break; } case'%':{ if (ch == '%') words[j++] = ch; words[j] = '\0'; ch = program[i++]; if (ch == '=') { words[j++] = ch; words[j] = '\0'; flag = 510; } else { i--; flag = 511; } break; } case',':{ words[j] = ch; words[j+1] = '\0'; flag = 512; break; } case'#':{ words[j] = ch; words[j+1] = '\0'; flag = 513; break; } case'@':{ words[j] = '#'; flag = 0; break; } default:{ flag = -1; break; } } return flag; } main() { i=0; printf("please input a program end with @"); do { ch = getchar(); program[i++] = ch; }while(ch != '@'); i = 0; do{ flag = Scan(program); if (flag == 200) { printf("(%2d,%4d)",flag,number); } else if (flag == -1) { printf("(%d,error)",flag); } else { printf("(%2d,%4s)",flag,words); } }while (flag != 0); system("pause"); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值