The Problem

JJTree is a part of JavaCC is a parser/scanner generator for Java. JJTree is a preprocessor for JavaCC that inserts parse tree building actions at various places in the JavaCC source. To follow along you need to understand the core concepts of parsing. Also review basic JJTree documentation and samples provided in JavaCC distribution (version 4.0).

JJTree is magically powerful, but it is as complex. We used it quite successfully at my startup www.moola.com. After some the basic research into the grammar rules, lookaheads, node annotations and prototyping I felt quite comfortable with the tool. However, just recently when I had to use JJTree again I hit the same steep learning curve as if I have never seen JJTree before.

How to write a tutorial that gets you back in shape quickly without forcing the full relearning?

The Solution

Here I capture my notes in a specific form that I do not have to face that same learning curve again in the future. You can think my approach as layered improvement to a grammar that follows these steps:

  • get lexer
  • complete grammar
  • optimize produced AST
  • define custom node
  • define actions
  • write evaluator

I always start simple and need to go more complex - this is exactly how I will document it. In each example I start with a trivial portion of grammar and then add some more to it to force specific behavior. New code is always in green. Let's hope this save all of us the relearning.

Reorder tokens from more specific to less specific

The token in TOKEN section can be declared in any order. But you have to pay very close attention to the order because the matching of tokens starts from the top and down the list until first matching token is found. For example notice how "interface" or "exception" are defined before STRING_LITERAL. If we had defined "interface" after STRING_LITERAL "interface" would never get matched,  STRING_LITERAL would.

TOKEN : {
  <INTERFACE: "interface" >
| < EXCEPTION: "exception" >
| < ENUM: "enum" >
| < STRUCT: "struct" > | < STRING_LITERAL: "'" (~["'","\n","\r"])* "'" >
| < TERM: <LETTER> (<LETTER>|<DIGIT>)* > | < NUMBER: <INTEGER> | <FLOAT> >
| < INTEGER: ["0"-"9"] (["0"-"9"])* >
| < FLOAT: (["0"-"9"])+ "." (["0"-"9"])* >
| < DIGIT: ["0"-"9"] >
| < LETTER: ["_","a"-"z","A"-"Z"] >
}

The ordering is the same reason why we can't just use "interface" inline in the definition of productions. The STRING_LITERAL will always match first.

Remove some nodes from final AST

Some nodes do not have any special meaning and should be excluded from the final AST.  This is done by using #void like this:

void InterfaceDecl() #void : {
}{
ExceptionClause()
|
EnumClause()
|
StructClause()
|
MethodDecl()
}

Add action to a production

You will definitely need to add actions to the production for your parser to be useful. Here I capture the text of the current token (t.image) and put it into jjThis node that will resolve to my custom node class TypeDecl. You bind a variable "t" to a token using "="; the action itself is in curly braces right after the production and can refer to current token as "t" and current AST node as "jjtThis".

void TypeDecl() : {
Token t;
}
{
<VOID>
|
t=<TERM> { jjtThis.name = t.image; } ("[]")?}
}

Here I further set isArray property to true only if "[]" is found after the <TERM>:

void TypeDecl() : {
Token t;
}
{
<VOID>
|
t=<TERM> { jjtThis.name = t.image; } ("[]" { jjtThis.isArray = true; } )?}
}

Multiple actions inside one production rule

Just as we have seen earlier you can access values of multiple token in one production rule. Notice how I declare two separate tokens "t" and "n". Here:

void ConstDecl() : {
Token t;
Token n;
}
{
LOOKAHEAD(2) t=<TERM> { jjtThis.name = t.image; } "=" n=<NUMBER> { jjtThis.value = Integer.valueOf(n.image); }
|
<TERM>
}

Lookaheads

There are certain points in complex  grammars that might not get parsed unambiguously using just one token look ahead. If you are writing high performance parser you might need to rewrite grammar. But if do not care about performance you can force lookahead for more that one symbol.

JJTree generator will give you a warning about ambiguities. Go the the rule it refers to and set lookahead of 2 or more like this:

void EnumDeclItem() : {}
{
LOOKAHEAD(2) <TERM> "=" <NUMBER>
|
<TERM>
}

Node return values

It is possible to return nodes from the productions, just like function return values. Here I am declaring the ASTTypeDecl will be returned.

ASTTypeDecl TypeDecl() : {
Token t;
}
{
<VOID>
|
t=<TERM> { jjtThis.name = t.image; } ("[]" { jjtThis.isArray = true; } )?} { return jjtThis; }
}

Once you start having a lot of expressions in one production it is better to group them together so return statement applies to all of them. The above example will actually result in a bug due to a fact that the return statement is attached to one branch of "|" production and not to both branches. We can easily fix the issue using parenthesis to force order of precendence:

ASTTypeDecl TypeDecl() : {
Token t;
}
{
(
<VOID>
|
t=<TERM> { jjtThis.name = t.image; } ("[]" { jjtThis.isArray = true; } )?}
) { return jjtThis; }
}

Build abstract syntax tree as you go

After you have all production return values you can build AST tree on the fly while parsing. Just provide found overloaded add() methods in the ASTInterfaceDecl class and call them like this:

void InterfaceDecl() #void : {
ASTExceptionClause ex;
ASTEnumClause en;
ASTStructClause st;
ASTMethodDecl me;
}
ex=ExceptionClause() { jjtThis.add(ex); }
|
en=EnumClause() { jjtThis.add(en); }
|
st=StructClause() { jjtThis.add(st); }
|
me=MethodDecl() { jjtThis.add(me); }
}

Use <EOF>

Quite often you can get your grammar written and start celebration when you notice that part of the file is not being parsed... This happens because you did not tell the parser to read all content till the end of file and it feels free to stop parsing at will. Force parsing to reach end of file by demanding <EOF> token at the top most production:

void InterfaceDecl() #void : {
}{
ExceptionClause()
|
EnumClause()
|
StructClause()
|
MethodDecl()
|
<EOF>
}

The Final Word

JJTree works incredibly well. No excuse to regex parsing no more... Don't even try to convince me!

Drop me a line if you need help with JJTree - will be glad to share the experiences with you.

References

  1. The JavaCC FAQ by Theodore S. Norvell

JJTree Tutorial for Advanced Java Parsing的更多相关文章

  1. Top 10 Books For Advanced Level Java Developers

    Java is one of the most popular programming language nowadays. There are plenty of books for beginne ...

  2. 转:Apache POI Tutorial

    Welcome to Apache POI Tutorial. Sometimes we need to read data from Microsoft Excel Files or we need ...

  3. 10 Things Every Java Programmer Should Know about String

    String in Java is very special class and most frequently used class as well. There are lot many thin ...

  4. Java 8 Stream Tutorial--转

    原文地址:http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ This example-driven tutori ...

  5. 【译】Core Java Questions and Answers【1-33】

    前言 译文链接:http://www.journaldev.com/2366/core-java-interview-questions-and-answers Java 8有哪些重要的特性 Java ...

  6. Java之数组篇

    动手动脑,第六次Tutorial--数组 这次的Tutorial讲解了Java中如何进行数组操作,包括数组声明创建使用和赋值运算,写这篇文章的目的就是通过实际运用已达到对数组使用的更加熟练,下面是实践 ...

  7. 《Java学习笔记(第8版)》学习指导

    <Java学习笔记(第8版)>学习指导 目录 图书简况 学习指导 第一章 Java平台概论 第二章 从JDK到IDE 第三章 基础语法 第四章 认识对象 第五章 对象封装 第六章 继承与多 ...

  8. Java集合框架的接口和类层次关系结构图

    Collection和Collections的区别 首先要说的是,"Collection" 和 "Collections"是两个不同的概念: 如下图所示,&qu ...

  9. JAVA CDI 学习(1) - @Inject基本用法

    CDI(Contexts and Dependency Injection 上下文依赖注入),是JAVA官方提供的依赖注入实现,可用于Dynamic Web Module中,先给3篇老外的文章,写得很 ...

随机推荐

  1. select默认选中

  2. python进阶(三) 内建函数getattr工厂模式

    getattr()这个方法最主要的作用是实现反射机制.也就是说可以通过字符串获取方法实例.  传入不同的字符串,调用的方法不一样. 原型:getattr(对象,方法名) 举个栗子: pyMethod类 ...

  3. 【2017-05-02】winform弹出警告框选择性操作、记事本制作、对话框控件和输入输出流

    一.winform弹出警告框选择性操作 MessageBox.Show()返回一个枚举类值(第一个参数为弹出窗口显示的内容,第二个参数为弹出窗口的标题,第三个参数为弹出窗口包含的按钮) 先新建一个变量 ...

  4. 【NOI 2015】品酒大会

    Problem Description 一年一度的"幻影阁夏日品酒大会"隆重开幕了.大会包含品尝和趣味挑战两个环节,分别向优胜者颁发"首席品酒家"和" ...

  5. Linux中通过Socket文件描述符寻找连接状态介绍

    针对下文的总结:socket是一种文件描述符 进程的打开文件描述符表 Linux的三个系统调用:open,socket,pipe 返回的都是一个描述符.不同的进程中,他们返回的描述符可以相同.那么,在 ...

  6. vs2015调试iisexpress无法启动的问题解决方案整理

    我上传的项目代码被同事下载之后使用iisexpress调试一直报错,iisexpress无法启动只能用自己本地的iis,我本地的代码却没问题,试了两种解决办法,问题解决了,在此记录一下也总结一下 方法 ...

  7. Qt 从菜单栏打开文件

    Qt从菜单栏的下拉菜单选择文件 构造函数中设置打开动作信息 //打开文件 m_menu = ui.menu; // m_menu->menuAction = new QAction(QIcon( ...

  8. Selenium3.6.0+Firefox55+JDK8.0配置

    一.安装JDK8.0(自行百度安装步骤) 二.在eclipse的偏好设置中选择java版本为8.0 三.Maven配置 <project xmlns="http://maven.apa ...

  9. Pandas 基础(6) - 用 replace() 函数处理不合理数据

    首先, 还是新建一个 jupyter notebook, 然后引入 csv 文件(此文件我已上传到博客园): import pandas as pd import numpy as np df = p ...

  10. android外包公司—技术分享:Android开发环境搭建(长年承接安卓应用外包)

    Android开发环境搭建 1.安装JDK 1.1.由于Android是基于java语言的.所以在开发过程中,首先要做的事儿就是安装JDK. 1.2.JDK的安装步骤: 设置环境变量:我的电脑---- ...