Adding a New Type to Java

Java doesn’t have a built-in vector math type (java.util.Vector is not meant for mathematics and isn’t a built-in type). Let’s say we wanted to add type vec so that we can do things like this:

 
vec x = [1, 2, 3];
 
vec y = [2, 9, 10];
 
vec z = x * y;

First, we need a strategy to execute this code. The easiest thing to do is to translate this down to raw Java. That means we have to figure out a mapping from input to output. Most of the input is pure Java, so we can just leave that stuff alone. The best way to change a few things and leave everything else alone is to “edit” the token stream (TokenRewriteStream if you’re using ANTLR). We know the start and stop tokens ([ and ]), so we can replace everything in between yielding ...

Get Language Implementation Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.