1.设计OPG语法分析程序。OPG分析程序的流程可参考课本P118页图5.8进行设计,其中对于文法及算符优先关系表,以课本P111页例5.3的文法和P112页的优先关系表(表5.5)为输入。
2.应用设计的分析程序对课本P116页的输入串i+i#进行一次OPG分析,输出归约过程(输出时非终结符由N代替), 并检验分析程序的正确性。
package Test4;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
String Vt = "+*|i()#";
String[][] OPG = {
{">","<","<","<","<",">",">"},
{">",">","<","<","<",">",">"},
{">",">","<","<","<",">",">"},
{">",">",">"," "," ",">",">"},
{"<","<","<","<","<","="," "},
{">",">",">"," "," ",">",">"},
{"<","<","<","<","<"," ","="},};
String stack = "#";
Scanner input = new Scanner(System.in);
System.out.println("请输入字符串:");
String str = input.nextLine();
boolean accept = false;
int n=0;
String action="";
System.out.println("步骤\t\t栈\t\t优先关系\t\t当前符号\t\t剩余输入串\t动作");
while(accept==false) {
int index = stack.length()-1;
String Stack = stack;
while(Vt.indexOf(stack.charAt(index))==-1) {
index--;
}
char priority = str.charAt(0);
String other = str.substring(1);
int a = Vt.indexOf(stack.charAt(index));
int b = Vt.indexOf(priority);
if(OPG[a][b]=="=") {
if(priority == '#') {
accept = true;
action = "接受";
}
else {
stack += str.charAt(0);
if(!"".equals(str)) {
priority = str.charAt(0);
str = str.substring(1);//???
}
action = "移进";
}
}
if(OPG[a][b]=="<") {
stack += str.charAt(0);
if(!"".equals(str)) {
priority = str.charAt(0);
str = str.substring(1);
}
action = "移进";
}
if(OPG[a][b]==">") {
if(a==5) {
stack = stack.substring(0, index-2)+"N";
while(stack.charAt(stack.length()-1)==stack.charAt(stack.length()-2)) {
stack = stack.substring(0,stack.length()-1);
}
}
else {
stack = stack.substring(0, index)+"N";
while(stack.charAt(stack.length()-1)==stack.charAt(stack.length()-2)) {
stack = stack.substring(0,stack.length()-1);
}
}
action = "归约";
}
n++;
System.out.println(n+"\t\t"+Stack+"\t\t"+OPG[a][b]+"\t\t"+priority+"\t\t"+other+"\t\t"+action);
if(OPG[a][b]==" ") {
break;
}
}
input.close();
}
}