📄 lex.cpp
字号:
#include "compile.h"
//******************************************************************/
//函数原型:void getSym()
//参数说明:无
//函数功能:词法分析主程序
//返回值 :无
//******************************************************************/
void getSym()
{
int j;
while(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t')
getChar();
/***********************标识符和保留字************************/
if( ifCharInStr(letter) )//当前字符ch是否在a...z字符集中
{
for(j=0; j<ID_LEN; j++)
{
ident[j]=ch;
getChar();
if( !ifCharInStr(letter_number) )//当前字符ch是否不在a...z,0...9字符集中
break;
}
for(j++; j<ID_LEN; j++)
ident[j]=' ';
for(j=0; j<NUM_OF_RESERVED_ID; j++)//检查字符串是否在保留字中
{
if( strcmp(ident,word[j]) == 0)//如果匹配成功
break;
}
if(j == NUM_OF_RESERVED_ID)//匹配未成功,不再保留字中
sym=IDENT;
else
sym=wsym[j];
}
else
{
/*****************************常数*****************************/
if( ifCharInStr(number) )//当前字符ch是否在0...9字符集中
{
sym=NUMBER;
num=0;
for(j=0; j<NUM_LEN; j++)
{
num = num*10 + ch - '0';
getChar();
if( !ifCharInStr(number) )//当前字符ch是否不在0...9字符集中
break;
}
if(j == NUM_LEN)
errorOccur(0);//常数位数过多
}
else
{
/*************************** := 和 : ***************************/
if(ch == ':')
{
getChar();
if(ch == '=')
{
sym=BECOMES;
getChar();
}
else
sym=NUL;
}
else
{
/*************************** < 和 <= ***************************/
if(ch == '<')
{
getChar();
if(ch == '=')
{
sym=LEQ;
getChar();
}
else
sym=LSS;
}
else
{
/*************************** > 和 >= ***************************/
if(ch == '>')
{
getChar();
if(ch == '=')
{
sym=GEQ;
getChar();
}
else
sym=GTR;
}
else
{
/********************** + - * / ( ) = , ; . ********************/
switch(ch)
{
case '+': sym=PLUS; break;
case '-': sym=MINUS; break;
case '*': sym=TIMES; break;
case '/': sym=SLASH; break;
case '(': sym=LPAREN; break;
case ')': sym=RPAREN; break;
case '=': sym=EQL; break;
case ',': sym=COMMA; break;
case ';': sym=SEMICOLON; break;
case '.': sym=PERIOD; break;
}
getChar();
}
}
}
}
}
return;
}
//******************************************************************/
//函数原型:void getChar()
//参数说明:无
//函数功能:从sourceProgram[]读入一个字符,放入ch中
//返回值 :无
//******************************************************************/
void getChar()
{
if( sCount == totalCount )
{
printf("program incomplete, yacc terminated \n\n");
exit(0);
}
else
{
ch = sourceProgram[sCount++];
}
}
//******************************************************************/
//函数原型:int ifCharInStr(char * str)
//参数说明:str: 字符集,如a...z,或者0...9,等
//函数功能:查找当前词法分析得到的字符ch是否在字符集str中
//返回值 :如果找到,返回1; 否则返回0;
//******************************************************************/
int ifCharInStr(char * str)
{
for(int j=0;str[j]!='\0';j++)
if(ch == str[j])
return 1;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -