一、实验目的
1、为初等函数运算语言构造词法分析器。
2、掌握生成词法分析器的方法,加深对词法分析原理的理解。
3、掌握设计、编制并调试词法分析程序的思想和方法。
二、实验内容
一、根据下面的要求设计初等函数运算语言的词法模式,并用正则式表达出来
1、 初等函数运算语言的常量为实数类型,其定义方式为实数的最一般书写方式,如:123.321。具体要求:不支持整数部分大于0时首数字为0;不支持小数点后结尾为0;不支持科学记数法;不支持仅为整数时有小数点。
2、 初等函数运算语言的变量采用与C语言的标识符定义一样的方式:首字符为字母或下划线;其他的为字母、数字及下划线的混合串;区分大小写;变量长度不超过32个字符。
3、 初等函数运算语言需要处理的函数仅为表一中所列举的内容。
4、 初等函数运算语言支持四则运算,其计算的符号与C语言相同,为:+-*/。
5、 初等函数运算语言的合法的分隔符包括:空格、制表符、、分行符圆括号(左、右)、分号。其中空格、制表符、分行符可以出现在任何两个不同的单词中间;圆括号(左、右)用于表达式中,用于改变运算的优先级,以及标识函数的参数;分号用于标识一个语句的结束。
6、 初等函数运算语言支持的常量还包括:PI,E。
二、根据设计的词法模式正规式,进行正规式->NFA->DFA->最小化DFA的转换步骤,给出最终的DFA。(纸上作业,即该步骤是在纸上完成,应在实验报告中表达出来)。
三、根据DFA构造词法分析程序。
四、对词法分析程序进行调试和测试。
三、词法模式正规式设计
四、正规式-->NFA
五、最小化DFA
六、记号表
七、实验结果
程序运行结果如下:
(实验编写、运行平台为IDEA)
八、词法分析程序主要代码
源程序关键函数代码如下:
//词法分析器
private static boolean Analyse() {
int currentIndex = 0;
//长度
int bufferLength = in.length();
//添加终结符
in += '\0';
//下一个字符的起点
int nextStartIndex = 0;
String temp;
int num = 0;
Hashtable<String , String> varTable = new Hashtable<>();
while (currentIndex < bufferLength) {
//是否为标识符
nextStartIndex = judgeVar(currentIndex);
if (nextStartIndex != -1) {
temp = in.substring(currentIndex,nextStartIndex);
//是否为关键字
//joey.Xzy
if (judgeFunction(temp)){
classes.add(tokenTable.get(temp));
names.add(temp);
values.add(temp);
//是否为枚举字面量
} else if (judgeEnumerator(temp)) {
classes.add(tokenTable.get(temp));
names.add(temp);
values.add(temp);
//就是标识符了
} else {
classes.add(tokenTable.get("variable"));
if (!varTable.containsKey(temp)) {
num++;
varTable.put(temp,"id" + String.valueOf(num));
}
names.add(varTable.get(temp));
values.add(temp);
}
currentIndex = nextStartIndex;
continue;
}
//是否为数值字面量
nextStartIndex = judgeNum(currentIndex);
if (nextStartIndex != -1) {
temp = in.substring(currentIndex,nextStartIndex);
classes.add(tokenTable.get("num"));
names.add(temp);
values.add(temp);
currentIndex = nextStartIndex;
continue;
}
//是否为分隔符
nextStartIndex = judgeSeparator(currentIndex);
if (nextStartIndex != -1) {
temp = in.substring(currentIndex,nextStartIndex);
classes.add(tokenTable.get(temp));
names.add(temp);
values.add(temp);
currentIndex = nextStartIndex;
continue;
}
//是否为运算符
nextStartIndex = judgeOperator(currentIndex);
if (nextStartIndex != -1) {
temp = in.substring(currentIndex,nextStartIndex);
classes.add(tokenTable.get(temp));
names.add(temp);
values.add(temp);
currentIndex = nextStartIndex;
continue;
}
//是否为输出符
nextStartIndex = judgeOut(currentIndex);
if (nextStartIndex != -1) {
temp = in.substring(currentIndex,nextStartIndex);
classes.add(tokenTable.get(temp));
names.add(temp);
values.add(temp);
//Joey.Xzy
currentIndex = nextStartIndex;
continue;
}
break;
}
if (currentIndex == bufferLength) {
return true;
}
System.out.print(in);
System.out.println("word illegal at "+ String.valueOf(currentIndex) + " " + in.charAt(currentIndex));
return false;
}
附:完整代码-->词法分析器