#语义分析
- 设计MiniC的上下文无关文法,在“Parser.jjt”文件中表示该文法,生成调试递归下降分析程序,以便对任意输入的符号串进行分析;
- 以文件流的形式读入要分析的C语言程序;
- 如果输入的源程序符合MiniC的语法规范,在文件中输出语法树。
#MiniC语法
〈程序〉 → int main() {〈语句块〉* }
〈语句块〉 →〈语句〉| {〈语句块〉* }
〈语句〉 →〈顺序语句〉|〈条件语句〉|〈循环语句〉
〈顺序语句〉→ [〈声明语句〉| 〈赋值语句〉] ”;”
〈声明语句〉→ int ID,ID,…,ID //思考如何表示
〈赋值语句〉→ ID =〈表达式〉
〈条件语句〉→ if〈条件〉〈语句块〉
〈循环语句〉→ while〈条件〉〈语句块〉
〈条件〉 →(〈表达式〉〈关系符〉〈表达式〉)
〈表达式〉 →〈表达式〉〈运算符〉〈表达式〉|(〈表达式〉)|ID|NUM
// 也可以使用javacc自动生成的 表达式(Expression)的文法
〈运算符〉 → +|-|*|/
〈关系符〉 → <|<=|>|>=|==|!=
#源代码
根据设计的MiniC语法添加词法规则声明,除去已有的声明,我添加了关键字,界限符等内容
TOKEN : /* KEYWORDS */
{
< MAIN : "main" >
| < INT : "int" >
| < VOID : "void" >
| < WHILE : "while" >
| < RETURN : "return" >
| < IF : "if" >
}
TOKEN : /*界符*/
{
<LC : "{">
| <RC : "}">
| <LS : "[">
| <RS : "]">
| <LP : "(">
| <RP : ")">
| <SE : ",">
| <CO : ";">
| <UL : "_">
| <COL : ":">
}
TOKEN : /*运算符*/
{
<EQUAL :"=">
| <PLUS :"+">
| <MINUS :"-">
| <TIMES :"*" >
| <DIVIDE :"/" >
}
在原有的表达式语法规则的基础上,添加了程序、语句块、语句等语法规则
void procedure():/*程序*/
{}
{
< VOID >< MAIN >< LP >< RP >< LC >(statementlock())*< RC >
}
void statementlock():/*语句块*/
{}
{
statement()
| < LC >(statementlock())*< RC >
}
void statement():/*语句*/
{}
{
sequence()
| condition()
| loop()
}
void sequence():/*顺序语句*/
{}
{
[declaration() | assignment()]< CO >
}
void declaration():/*声明语句*/
{}
{
< INT >Identifier() (< SE >Identifier())*
}
void assignment():/*赋值语句*/
{}
{
Identifier() < EQUAL >Expression()
}
void condition():/*条件语句*/
{}
{
< IF >term()statementlock()
}
void loop():/*循环语句*/
{}
{
< WHILE >term()statementlock()
}
void term():/*条件*/
{}
{
< LP >Expression()operator()Expression()< RP >
}
void operator():/*运算符*/
{}
{
"<"
| "<="
| ">"
| ">="
| "=="
| "!="
}
修改jjt文件中的main方法,使其从文件中读取源程序代替控制台输入源程序
System.out.println("Reading from standard input...");
System.out.print("Enter an expression like \"1+(2+3)*var;\" :");
File fp = new File("test.txt");
InputStream in = null;
try {
in = new FileInputStream(fp);
new Parser(in);
}catch(IOException e) {
System.out.println("File open error!");
}
//new Parser(System.in);
try
{
SimpleNode n = Parser.Start();
n.dump("");
System.out.println("Thank you.");
}
catch (Exception e)
{
System.out.println("Oops.");
System.out.println(e.getMessage());
}
在SimpleNode.java文件中修改dump()方法,使其将语法树输出至文件代替输出至控制台。运行程序后在out.txt文件中可以查看输出的语法树。
public void dump(String prefix) {
try {
File file = new File("out.txt");
FileOutputStream out = new FileOutputStream(file, true);
byte [] a = (toString(prefix)+"\r\n").getBytes();
out.write(a);
out.close();
// out = new FileOutputStream();
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode)children[i];
if (n != null) {
n.dump(prefix + " ");
}
}
}
} catch (Exception e) {
// TODO: handle exception
}
// System.out.println(toString(prefix));
// if (children != null) {
// for (int i = 0; i < children.length; ++i) {
// SimpleNode n = (SimpleNode)children[i];
// if (n != null) {
// n.dump(prefix + " ");
// }
// }
// }
}
#运行结果
左边为输入的源程序,右边为在out.txt文件中输出的生成树。