大工软院编译上机1词法分析课案Word文档格式.docx
《大工软院编译上机1词法分析课案Word文档格式.docx》由会员分享,可在线阅读,更多相关《大工软院编译上机1词法分析课案Word文档格式.docx(9页珍藏版)》请在冰点文库上搜索。
for
1
:
17
if
2
=
18
then
3
<
20
else
4
21
while
5
22
do
6
23
letter(letter+digit)*
10
24
digitdigit*
11
25
+
13
;
26
-
14
(
27
*
15
)
28
/
16
#
词法分析程序的功能
输入:
源程序
输出:
二元组(词法记号,属性值/其在符号表中的位置)构成的序列。
例如:
对源程序
x:
=5;
if(x>
0)thenx:
=2*x+1/3;
elsex:
=2/x;
#
经词法分析后输出如下序列:
(10,’x’)(18,:
=)(11,5)(26,;
)(2,if)(27,()……
1.几点说明:
(1)关键字表的初值。
关键字作为特殊标识符处理,把它们预先安排在一张表格中(称为关键字表),当扫描程序识别出标识符,查关键字表。
如能查到匹配的单词,则该单词的关键字,否则为一般标识符。
关键表为一个字符串数组,其描述如下:
char*keyword[6]={”for”,”if”,”then”,”else”,”while”,”do”};
(2)程序中需要用到的主要变量为token,id和num.
1)id用来存放构成词法单元的字符串;
2)num用来存放整数(可以扩展到浮点数和科学计数法表示);
3)token用来存放词法单元的词法记号。
可以参考下面的代码:
do{
lexical();
//将词法单元对应的记号保存到token中,属性值保存到num或者id中
switch(token){
case11:
printf("
(token,%d\n)"
num);
break;
case-1:
printf("
error!
\n"
);
break;
default:
(%d,%s)\n"
token,id);
}
}while(token!
=0);
#include<
iostream>
string>
fstream>
queue>
cstdlib>
usingnamespacestd;
stringkeyword[6]={"
for"
"
if"
then"
else"
while"
do"
};
boolisLETTER(chartemp)
{
if(temp>
='
a'
&
&
temp<
z'
returntrue;
else
returnfalse;
}
boolisDIGIT(chartemp)
0'
9'
returntrue;
returnfalse;
boolisID(stringtemp)
boolflag=true;
if(!
isLETTER(temp[0]))
flag=false;
for(inti=1;
i<
temp.length()&
flag;
i++)
{
if(!
(isLETTER(temp[i])||isDIGIT(temp[i])))
flag=false;
}
returnflag;
boolisNUM(stringtemp)
for(inti=0;
(temp[i]>
temp[i]<
))
voidgetkey(stringtemp,int&
key)
if(temp=="
)key=1;
elseif(temp=="
)key=2;
)key=3;
)key=4;
)key=5;
)key=6;
elseif(isID(temp))key=10;
elseif(isNUM(temp))key=11;
+"
)key=13;
-"
)key=14;
*"
)key=15;
/"
)key=16;
"
)key=17;
="
)key=18;
)key=20;
)key=21;
)key=22;
)key=23;
)key=24;
)key=25;
)key=26;
("
)key=27;
)"
)key=28;
#"
)key=0;
elsekey=-1;
intmain()
stringtemp;
chara;
intkey;
queue<
aqueue;
char*array=newchar[20];
ifstreamfile;
file.open("
test.txt"
file)
cout<
can'
topen'
test.txt'
"
endl;
exit
(1);
a=file.get();
while(!
file.eof())
while(a=='
'
{
}
flag=true;
inti=0;
array[i++]=a;
while(isDIGIT(a))
a=file.get();
if(isDIGIT(a))
array[i++]=a;
else
flag=false;
if(isLETTER(a)&
flag)
while(isLETTER(a)||isDIGIT(a))
{
if(isLETTER(a)||isDIGIT(a))
}
if(flag)
switch(a)
case'
'
:
if(a=='
{
array[i++]=a;
a=file.get();
break;
||a=='
{
array[i++]=a;
a=file.get();
}
if(a=='
}
default:
stringt(array,i);
aqueue.push(t);
aqueue.empty())
temp=aqueue.front();
aqueue.pop();
getkey(temp,key);
switch(key)
case-1:
cout<
//case0:
key<
temp<
default:
return0;