使用Java语言编写PL/0编译程序的语法分析程序
时间: 2023-11-25 20:07:22 浏览: 105
以下是使用 Java 语言编写的 PL/0 语法分析程序,包括词法分析和语法分析两部分:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PL0Parser {
private BufferedReader reader;
private int lookahead;
public PL0Parser(String filename) throws IOException {
reader = new BufferedReader(new FileReader(filename));
lookahead = reader.read();
}
public void parse() throws IOException {
program();
reader.close();
}
private void program() throws IOException {
block();
if (lookahead != '.') {
error("期望遇到句号");
}
match('.');
}
private void block() throws IOException {
if (lookahead == 'c') {
constDeclaration();
}
if (lookahead == 'v') {
varDeclaration();
}
while (lookahead == 'p' || lookahead == 'c' || lookahead == 'v' || lookahead == 'b') {
if (lookahead == 'p') {
procedureDeclaration();
} else if (lookahead == 'c') {
constDeclaration();
} else if (lookahead == 'v') {
varDeclaration();
} else {
block();
match(';');
}
}
statement();
}
private void constDeclaration() throws IOException {
match('c');
do {
ident();
match('=');
number();
} while (lookahead == ',');
match(';');
}
private void varDeclaration() throws IOException {
match('v');
ident();
while (lookahead == ',') {
match(',');
ident();
}
match(';');
}
private void procedureDeclaration() throws IOException {
match('p');
ident();
match(';');
block();
match(';');
}
private void statement() throws IOException {
if (lookahead == 'i') {
match('i');
ident();
match(':');
expression();
match(';');
} else if (lookahead == 'w') {
match('w');
expression();
match('d');
statement();
} else if (lookahead == 'c') {
match('c');
expression();
match('t');
statement();
if (lookahead == 'e') {
match('e');
statement();
}
} else if (lookahead == 'r') {
match('r');
ident();
match(';');
} else if (lookahead == 'b') {
match('b');
block();
match('e');
}
}
private void expression() throws IOException {
if (lookahead == '+' || lookahead == '-') {
match(lookahead);
}
term();
while (lookahead == '+' || lookahead == '-') {
match(lookahead);
term();
}
}
private void term() throws IOException {
factor();
while (lookahead == '*' || lookahead == '/') {
match(lookahead);
factor();
}
}
private void factor() throws IOException {
if (lookahead == '(') {
match('(');
expression();
match(')');
} else if (lookahead == 'n') {
match('n');
} else {
ident();
}
}
private void ident() throws IOException {
if (lookahead >= 'a' && lookahead <= 'z') {
match(lookahead);
} else {
error("期望遇到标识符");
}
}
private void number() throws IOException {
if (lookahead >= '0' && lookahead <= '9') {
match(lookahead);
} else {
error("期望遇到数字");
}
}
private void match(int c) throws IOException {
if (lookahead == c) {
lookahead = reader.read();
} else {
error("语法错误");
}
}
private void error(String message) {
System.err.println(message);
System.exit(1);
}
}
```
该程序的输入为 PL/0 代码文件的路径,输出为语法错误信息或无输出(表示语法分析成功)。使用时只需创建一个 `PL0Parser` 对象并调用它的 `parse()` 方法即可。
阅读全文