4

I want to create a Java transpiler that will read nearly-Java code (call it JavaHash) and emit "pure" Java code on the other end. In particular, I want to add a new token that is the hashtag "#" in front of a hashmap member so that I might access it similar to a JavaScript hash object:

Map<String, String> foo = new HashMap<String, String>();
...
foo.put("name", "Roger");
...
String name = #foo.name;

I can't get the JavaParser to do anything but throw an error on the "#" hashtag.

Are there ways to catch tokens before they are parsed?

1 Answers1

6

This is very far from trivial, but doable.

JavaParser is based on JavaCC, it uses the following grammar to generate parser code. The parser then creates an abstract syntax tree using code model classes.

If you want to add new language elements, you will need to:

  • implement code model classes;
  • extend the grammar used for parser generation.

This is not so easy, you will need good knowledge and understanding of JavaCC. But it is absolutely doable.

The rest is peanuts. You'll write a visitor and use it to traverse the AST. Once you've encountered the node of the appropriate type, simply transform the part of AST into "normal" Java and serialize.

By the way, JavaParser is a very good basis to build something like what you want. So congratulations to your choice, this is half of the deal, actually.

lexicore
  • 42,748
  • 17
  • 132
  • 221