简体   繁体   中英

Using the Visitor Pattern with JavaCC and JJtree

I wrote a scanner and parser using JavaCC and JJtree that generates an abstract syntax tree, and then I wrote a PrintVisitor class with a Visitor object for each node in the tree. However, after running the jjt file through JJtree and JavaCC, the Java compiler gave me this error:

PrintVisitor.java:1: error: PrintVisitor is not abstract and does not override
abstract method visit(Command, Object) in GrammarVisitor

The reader will note that only one visitor object caused this error, even though I had many other visitor objects implemented in the exact same way for the other nodes in the tree. Why does only

visit(Command, Object) 

cause an error, and how do I fix it?

As it turns out, the problem stems from using previously generated files from JJtree and JavaCC after changes have been made to the original jjt file and/or to the PrintVisitor class. Thanks to @Theodore Norvell for pointing this out.

As the JJtree Reference Documentation, found here , says,

JJTree provides some basic support for the visitor design pattern. If the VISITOR option is set to true JJTree will insert an jjtAccept() method into all of the node classes it generates, and also generate a visitor interface that can be implemented and passed to the nodes to accept.

The name of the visitor interface is constructed by appending Visitor to the name of the parser. The interface is regenerated every time that JJTree is run, so that it accurately represents the set of nodes used by the parser. This will cause compile time errors if the implementation class has not been updated for the new nodes.

To avoid problems like mine, I recommend creating a completely new directory containing only the .jjt file and the Visitor class, and then running JJtree and JavaCC on those. As I learned, it is suprisingly easy to miss deleting one or two old files, and then nothing works correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM