SPECIAL EDITION FOR GJ
Standard JTB Home
(Java grammar that includes the Java 1.1 language extensions provided by
JavaCC) as the grammar file.
The function of this example is to count how many tokens, including <EOF>,
are in the input Java file.
First run JTB GJ1.1.1 on Java1.1.jj, then JavaCC on jtb.out.jj:
% jtbgj Java1.1.jjDownload Main.java to the directory where you run JTB and JavaCC, and download MyInt.java and Counter.java to the visitor directory generated by JTB. Finally, compile Main.java with GJ compiler:
% gjc Main.javaNow you can run the example on any Java source file by:
% java Main < inputfile.javaIt will tell you how many tokens are there in inputfile.java. The following paragraphs will go through the source files of this example and show you how generic types are specified in visitors. Let's start from MyInt.java:
package visitor;An object of MyInt class will be passed on as an argument during the syntax tree traversal. The reason I put MyInt in the visitor package is that both Main class and Counter class need it. The next is Counter.java:
package visitor;Counter is a visitor that extends GJDepthFirst. It specifies the type parameters by GJDepthFirst<MyInt,MyInt>. The first MyInt stands for the return type, and the second MyInt is the type of the argument. In this example, the return value is useless. What Counter does is to increase count field of the object of MyInt. An object of MyInt will be passed on as the argument, so at the end of the syntax tree traversal, it will record the total number of the tokens. The last file is Main.java:
import syntaxtree.*;There's nothing special about Main.java. It simply calls the parser (the syntax tree is constructed automatically during parsing) and starts the visitor. This example doesn't have to be implemented this way. The whole purpose is to demonstrate the usage of GJDepthFirst and GJVisitor.
package visitor;The only difference is that with GJ, there is no type casting at all. You will find GJ extremely uesful when your visitor is complex and you try to pass parameters and get return values. All the mismatch types can be found at compile-time in GJ.
standard JTB Examples page, and see how to achieve the same goal using standard Java.
You can still find some type castings in the above example. It is because the grammar is not well organized. By properly revising the grammar, your visitor can be totally type-casting free, though the revised grammar may be a little bit longer. Below is a revised version of the same example where all the classes are type-casting free:
|Maintained by Wanjun Wang, email@example.com.||Created September 4, 1997.
Last modified Sep. 25, 1999.