一、实验题目

设计、编制、调试一个识别一简单语言单词的词法分析程序。程序能够识别基本字、标识符、无符号整数、浮点数、运算符和界符)。单词符号及种别表如下:

单词符号

种别编码

begin

1

if

2

then

3

while

4

do

5

end

6

l(l|d)*

10

dd*

11

+

13

-

14

*

15

/

16

:

17

:=

18

<

20

<>

21

<=

22

>

23

>=

24

=

25

;

26

(

27

)

28

#

0

 

 

二、实验目的

设计、编制并调试一个词法分析程序,加深对词法分析原理的理解。

、实验要求

词法分析程序需具备词法分析的功能:

输入:所给文法的源程序字符串。(字符串以“#”号结束)

输出:二元组(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)……

四、实验步骤

(包括基本设计思路、流程框图、算法设计、函数相关说明、输入与输出以及程序运行结果)

基本设计思路

  根据实验要求,我们要对词法进行分析。首先我们先将实验中的单词符号及种别表放在一个二维数组中,便于我们进行查找。我们将从文件中读取代码段,然后从左到右进行扫描,在线的将扫描的结果输出到终端显示出来。

我们的文件组织如图:

                                   

编译原理 -- 词法分析程序设计_编译原理

 其中 In.txt 中保存了分析的代码 。

                                  

编译原理 -- 词法分析程序设计_i++_02

函数说明

int findc(string str) ; //  找到str在单词表中的编号。

int check() ; // 返回ss栈字符串

int getsym(char *str) ; // 从左到右进行词法分析

运行截图

             

编译原理 -- 词法分析程序设计_编译原理_03


                               

代码 : 

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <algorithm>
using namespace std ;
const int MAX = 1005 ;
char iword[50][50] = {
"#","begin","if","then","while","do","end","","","","",
"l(l|d)*","dd*","+","-","*","/",":",":=",
"<","<>","<=",">",">=","=",";","(",")" ,
} ;
int wsym[100] ; // 保留字单词种别
char id[100] ;
int num ;
int cnt ;
int y[110];
stack<char> st ;
string ss = "" ;
char tmp[100] ;
int findc(string a ) {
memset(tmp,'\0',sizeof(tmp));
for(int i = 0 ;i<a.size() ; i++ ) {
tmp[i] = a[i] ;
}
tmp[a.size()] = '\0' ;
for(int i = 0 ; i<29; i++ ) {
if(!strcmp(tmp,iword[i]) ){
return i ;
}
}
return 0 ;
}
int check() {
ss.clear() ;
while(!st.empty()) {
ss+=st.top() ;
st.pop() ;
}
reverse(ss.begin(),ss.end()) ;
int t = findc(ss) ;
return t ;
}
int getsym(char *str) { // 词法分析
int len = strlen(str) ;
for(int i = 0 ; i<len; i++) {
if(str[i] >='a' && str[i] <='z') {
while(str[i]!=' ' && (str[i] >='a'&&str[i]<='z' ) ) {
st.push(str[i]) ;
i++ ;
}
int syn = check();
if(syn) { // 是关键字
printf("(%d,%s)",syn,iword[syn]) ;
}
else{ // 不是关键子 , 而是标识符
printf("(%d,%s)",10,tmp);
i-- ;
}
}
else if(str[i] >='0' && str[i] <='9'){ // 如果是数字
string number = "" ;
while(str[i] >='0' && str[i] <='9'){
number+=str[i] ;
i++ ;
}
cout<<"("<<11<<","<<number<<")";
i-- ;
}
else if (str[i]!=' '){
if(str[i]!=':'){
string s ="";
s+=str[i];
int num =findc(s) ;
cout<<"("<<findc(s)<<","<<s<<")" ;
if(str[i] =='#') {
return 0 ;
}
}
else if(str[i]==':'&&str[i+1]=='='){
string s =":=";
int num =findc(s) ;
cout<<"("<<findc(s)<<","<<s<<")" ;
i++ ;
}
}
}

}
char r[100] ;
int main(){
//freopen("in.txt","r",stdin) ;
//freopen("out.txt","w",stdout) ;
FILE *fp = fopen("in.txt","r");
if(!fp) {
printf("error\n") ;
exit(0) ;
}
char ch ;
fgets(r,100,fp);
printf("代码 : %s\n分析结果 : \n",r) ;
getsym(r);
cout<<endl ;
return 0 ;
}