本章在第3A章源代码基础上继续完善基于Antlr自动化的解析器,解释执行第5章解析的复合语句,赋值语句和表达式等相关中间码。并仿照第5章的简化标准,将一些东西简化掉,尽量能让你从最简处入手,掌握Antlr自动化构建解析器的第一步。
==>> 本章中文版源代码下载:svn co http://wci.googlecode.com/svn/branches/ch5_antlr/ 源代码使用了UTF-8编码,下载到本地请修改!
好的工具事半功倍,Antlr亦如此。antlr.org上有一个很有特色的工具antlrwors。如果使用Eclipse,可以安装插件antlrv3ide。两个工具的主要特色是可视化的创建EBNF语法,就如同你在前面章节看到的语法图一样。对于我来说,比较习惯antlrworks,它有良好的调试功能和DFA分析功能。
1 带AST构造的语法
1: program:
2: compound_statement DOT!;
3: compound_statement:
4: BEGIN statement_list END ->^(COMPOUND statement_list);
5: assignment_statement:
6: ID ASSIGN expression -> ^(ASSIGN ID expression);
7: statement:
8: compound_statement | assignment_statement;
9: statement_list:
10: statement (SEMI statement)* SEMI? -> statement+;
11: expression:
12: simple_expression (rel_ops^ simple_expression)?;
13: rel_ops:
14: LT | LE | GT | GE | NOT_EQUAL;
15: simple_expression:
16: signedterm (add_ops^ term)*;
17: signedterm:
18: (a=PLUS | a=MINUS)? term ->{a!=null&&a.getType()==MINUS}?^(NEGATE term)->term;
19: add_ops:
20: PLUS | MINUS | OR;
21: term:
22: factor (mul_ops^ factor)*;
23: mul_ops:
24: STAR | SLASH | DIV | MOD | AND;
25: factor:
26: ID | NUMBER | STRING | NOT^ factor | LPAREN! expression RPAREN!;