编译原理C语言词法分析器
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
编译原理 C语言词法分析器
一、实验题目
编制并调试C词法分析程序。
a.txt源代码:
•main() {
int sum=0 ,it=1;/* Variable declaration*/
if (sum==1)
it++;
else
it=it+2;
}•
设计其词法分析程序,能识别出所有的关键字、标识符、常数、运算符(包括复合运算符,如++)、界符;能过滤掉源程序中的注释、空格、制表符、换行符;并且能够对一些词法规则的错误进行必要的处理,如:标识符只能由字母、数字和下划线组成,且第一个字符必须为字母或下划线。实验要求:要给出所分析语言的词法说明,相应的状态转换图,单词的种别编码方案,词法分析程序的主要算法思想等。
二、实验目的
1、理解词法分析在编译程序中的作用;
2、掌握词法分析程序的实现方法和技术;
3、加深对有穷自动机模型的理解。
三、主要函数
四、设计
1.主函数void main ( )
2. 初始化函数void load ( )
3. 保留字及标识符判断函数void char_search(char *word)
4. 整数类型判断函数void inta_search(char *word)
5. 浮点类型判断函数void intb_search(char *word)
6. 字符串常量判断函数void cc_search(char *word)
7. 字符常量判断函数void c_search(char *word)
同4、5函数图
8.主扫描函数void scan ( )
五、关键代码
#include
#include
#include
char *key0[]={" ","auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if" ,"int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","_Complex","_Imaginary"," union","unsigned","void","volatile","while"};
/*保留字表*/
char *key1[]={" ","(",")","[","]","{","}",",",";","'"};
/*分隔符表*/
char *key2[]={" ","+","-","*","/","%","<",">","==",">=","<=","!=","!","&&","||","<<",">>","~","|","^","&","=","?:","->","++","--",".","+ =","-=","*=","/="};
/*运算符表*/
int xx0[35],xx1[10],xx2[31];
int temp_key3=0,temp_c40=0,temp_c41=0,temp_c42=0,temp_c43=0;
/******* 初始化函数*******/
void load()
{
int mm;
for (mm=0;mm<=34;mm++)
{
xx0[mm]=0;
}
for (mm=0;mm<=9;mm++)
{
xx1[mm]=0;
}
for (mm=0;mm<=30;mm++)
{
xx2[mm]=0;
}
FILE *floading;
if ((floading=fopen("key0.txt","w"))==NULL)
{
printf("Error! Can't create file : key0.txt");
return;
}
fclose (floading);
/*建立保留字表文件:key0.txt*/
if ((floading=fopen("key1.txt","w"))==NULL)
{
printf("Error! Can't create file : key1.txt");
return;
}
/*建立分隔符表文件:key1.txt*/
if ((floading=fopen("key2.txt","w"))==NULL)
{
printf("Error! Can't create file : key2.txt");
return;
}
fclose(floading);
/*建立运算符表文件:key2.txt*/
if ((floading=fopen("key3.txt","w"))==NULL)
{
printf("Error! Can't create file : key3.txt");
return;
}
fclose (floading);
/*建立标识符表文件:key3.txt*/
if ((floading=fopen("c40.txt","w"))==NULL)
{
printf("Error! Can't create file : c40.txt");
return;
}
fclose (floading);
/*建立整数类型常量表文件:c40.txt*/
if ((floading=fopen("c41.txt","w"))==NULL)
{
printf("Error! Can't create file : c41.txt");
return;
}
fclose (floading);
/*建立浮点类型常量表文件:c41.txt*/
if ((floading=fopen("c42.txt","w"))==NULL)
{
printf("Error! Can't create file : c42.txt");
return;
}
fclose (floading);
/*建立字符类型常量表文件:c42.txt*/
if ((floading=fopen("c43.txt","w"))==NULL)
{
printf("Error! Can't create file : c43.txt");
return;
}
fclose (floading);
/*建立字符串类型常量表文件:c43.txt*/
if ((floading=fopen("defination.txt","w"))==NULL) {
printf("Error! Can't create file : defination.txt");
return;
}