编译原理实验报告(一)----词法分析程序Word文档格式.doc
《编译原理实验报告(一)----词法分析程序Word文档格式.doc》由会员分享,可在线阅读,更多相关《编译原理实验报告(一)----词法分析程序Word文档格式.doc(11页珍藏版)》请在冰豆网上搜索。
![编译原理实验报告(一)----词法分析程序Word文档格式.doc](https://file1.bdocx.com/fileroot1/2022-10/4/90755f3a-543e-491d-a19a-ebcce0012761/90755f3a-543e-491d-a19a-ebcce00127611.gif)
字符处理函数
intoperation(chars[],inti);
运算符处理函数
voidseti(chars[]);
标识符建立函数
voidsetc(chars[]);
常量建立函数
voidcfile(chars1[],chars2[],intm);
将词和词所在表中位置写入编译后文件
voiderror1(chars[]);
字符处理出错报告
voiderror2(chars[]);
标识符处理出错报告
voiderror3(chars[]);
运算符处理出错报告
voidopenall();
打开所有文件
voidwriteall();
将四个表写入文件
voidcloseall();
关闭所有文件
下面简要分析一下词法分析程序的运行流程:
能否打开所要编译的C语言文件
否
报错
能
判断当前字符是否是文件结束符
是
结束
从源程序中读入一行到数组缓冲区
否
判断当前字符是否是’\n’
是
判断当前字符是否是字母
转关键字和标识符处理
判断当前字符是否是数字
转数字处理
判断当前字符是否是运算符
转运算符处理
【程序调试】
现有源程序a.c清单如下:
#include<
stdio.h>
intmain(intargc,char*argv[])
{charch;
inti;
ch='
a'
;
ch=ch+32;
i=ch;
printf("
%did%c\n"
i,ch);
/*打印*/
return0;
}
运行词法分析程序后,显示如下结果:
after_com.txt文件:
#[p--2]
include[i--0]
<
[p--14]
stdio.h[i--1]
>
[p--16]
int[k--2]
main[i--2]
([p--7]
argc[i--3]
[p--6]
char[k--0]
*[p--9]
argv[i--4]
[[p--18]
][p--21]
)[p--8]
{[p--23]
ch[i--5]
[p--13]
i[i--6]
=[p--15]
'
[p--19]
a[i--7]
+[p--10]
32[c--0]
printf[k--33]
"
[p--1]
%[p--4]
d[i--8]
id[i--9]
c[i--10]
\[p--20]
n[i--11]
return[k--28]
0[c--1]
}[p--25]
key.txt关键字文件:
0char
1short
2int
3unsigned
4long
5float
6double
7struct
8union
9void
10enum
11signed
12const
13volatile
14typedef
15auto
16register
17static
18extem
19break
20case
21continue
22default
23do
24else
25for
26goto
27if
28return
29switch
30while
31sizeof
32txt
33printf
34FILE
35fopen
36NULL
37fclose
38exit
39r
40read
41close
42w
43fprintf
id.txt标识符文件:
0include
1stdio.h
2main
3argc
4argv
5ch
6i
7a
8d
9id
10c
11n
operation.txt运算符文件:
0!
1"
2#
3$
4%
5&
6,
7(
8)
9*
10+
11-
12:
13;
14<
15=
16>
17?
18[
19'
20\
21]
22.
23{
24||
25}
26!
=
27>
28<
29==
30++
31--
32&
&
33/*
34*/
const.txt常量文件:
032
10
结果完全正确。
词法分析程序如下:
#include<
string.h>
stdlib.h>
ctype.h>
#defineSIZE256
#definenull0
intline=0,error=0,mark1=0,mark2=0;
char*sname;
FILE*sfp,*nfp,*ifp,*kfp,*cfp,*pfp;
/*--------------------------------------------------------------------*/
charib[50][20];
charcb[50][10];
charkb[44][10]={"
char"
"
short"
int"
unsigned"
long"
float"
double"
struct"
union"
void"
"
enum"
signed"
const"
volatile"
typedef"
auto"
register"
static"
extem"
break"
case"
continue"
default"
do"
else"
for"
goto"
if"
return"
switch"
while"
sizeof"
txt"
printf"
FILE"
fopen"
NULL"
fclose"
exit"
r"
read"
close"
w"
fprintf"
};
charpb[36][5]={"
!
\"
\#"
\$"
%"
("
)"
*"
+"
-"
:
="
?
["
\\"
]"
."
{"
||"
}"
=="
++"
--"
/*"
*/"
/*----------定义了四个二元数组存放四个表--------------------------------*/
{charsbuff[SIZE];
charnbuff[SIZE];
inti;
/*---------------------------------------------------------------------*/
intnumber(