本章在第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!;

相关文章:

  • 2021-07-05
  • 2021-12-07
  • 2021-11-20
  • 2021-08-13
  • 2022-01-30
  • 2021-07-25
  • 2021-12-10
  • 2022-01-14
猜你喜欢
  • 2021-09-02
  • 2021-10-16
  • 2021-10-16
  • 2022-02-02
  • 2021-10-27
  • 2021-08-05
  • 2021-07-28
相关资源
相似解决方案