用Java语言给上面的分析表编写LR(0)分析器
时间: 2024-03-16 17:42:45 浏览: 16
以下为基于LR(0)分析表的Java代码实现:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class LR0Parser {
private static final int[][] GOTO_TABLE = {
{1, 3},
{0, 0},
{1, 3},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0}
};
private static final int[][] ACTION_TABLE = {
{2, 0, 4, 0, 0},
{0, 0, 0, 0, 1},
{5, 6, 4, 0, 0},
{5, 6, 0, 0, 0},
{0, 0, 0, 0, 2},
{5, 0, 4, 0, 0},
{5, 6, 4, 0, 0},
{0, 6, 0, 4, 4},
{5, 0, 4, 0, 0},
{5, 6, 0, 1, 1},
{0, 6, 0, 3, 3}
};
public static void main(String[] args) {
String input = "a+a*a";
Stack<Integer> stateStack = new Stack<>();
Stack<Character> symbolStack = new Stack<>();
stateStack.push(0);
int index = 0;
while (index < input.length()) {
int currentState = stateStack.peek();
char currentSymbol = input.charAt(index);
int action = getAction(currentState, currentSymbol);
if (action > 0) {
stateStack.push(action);
symbolStack.push(currentSymbol);
index++;
} else if (action < 0) {
int reduceLength = -action;
String production = reduce(reduceLength);
if (production.equals("E->T")) {
symbolStack.pop();
stateStack.pop();
stateStack.push(GOTO_TABLE[stateStack.peek()][0]);
symbolStack.push('E');
} else if (production.equals("E->E+T")) {
symbolStack.pop();
symbolStack.pop();
stateStack.pop();
stateStack.push(GOTO_TABLE[stateStack.peek()][0]);
symbolStack.push('E');
} else if (production.equals("T->a")) {
stateStack.pop();
stateStack.push(GOTO_TABLE[stateStack.peek()][1]);
symbolStack.push('T');
} else if (production.equals("T->(E)")) {
symbolStack.pop();
stateStack.pop();
symbolStack.pop();
stateStack.pop();
stateStack.push(GOTO_TABLE[stateStack.peek()][1]);
symbolStack.push('T');
}
} else {
System.out.println("Invalid input");
break;
}
}
int currentState = stateStack.peek();
int action = ACTION_TABLE[currentState][4];
if (action == 1) {
System.out.println("Accepted");
} else {
System.out.println("Rejected");
}
}
private static int getAction(int state, char symbol) {
int index = -1;
switch (symbol) {
case 'a':
index = 0;
break;
case '+':
index = 1;
break;
case '(':
index = 2;
break;
case ')':
index = 3;
break;
case '$':
index = 4;
break;
default:
break;
}
return ACTION_TABLE[state][index];
}
private static String reduce(int length) {
Map<Integer, String> productionMap = new HashMap<>();
productionMap.put(1, "E->E+T");
productionMap.put(2, "E->T");
productionMap.put(3, "T->T*a");
productionMap.put(4, "T->a");
productionMap.put(5, "T->(E)");
return productionMap.get(length);
}
}
```
注:上述代码中的 ACTION_TABLE 和 GOTO_TABLE 分别对应于前面所给的 LR(0)分析表中的 ACTION_TABLE 和 GOTO_TABLE。输入的字符串为"a+a*a"。