personal experiences and code :)

Monday, July 30, 2007

jatran: java to scala (and actionscript) transformer

I posted this message to the scala list earlier today:

jatran is a tool I wrote last summer to transform Java source files into Actionscript 2

It is based on Andy Tripp's JavaEmitter and the updated java15.g antlr grammar by Michael Studman

I have dusted it off and added a preliminary implementation for transforming Java to Scala (and actionscript 3)
Most of the notes for performing the transformations come from Burak Emir's notes here as well as A. Sundararajan's notes here and the ScalaRef

it is by no means meant to create a fully useful scala (or actionscript) file, but it gets some of the manual work out of the way
here are a few things basic things that work currently:

for Scala:
- interfaces are changed to traits; implements is changed to extends/with
- all static class members are pushed into an object with the same TypeName as the class definition
- a few java keywords with annotation equivalents in scala (like transient, volatile, native) are converted
- java 1.5 @Override annotations are converted into the override keyword
- method definitions are changed to 'def'; public modifiers are dropped
- throws clause is changed to scala throws annotations
- variable definitions are changed from Type type to the type:Type (post-colon) syntax
- final variables are converted into scala vals
- Type params are transformed into scala syntax
- instanceof and type casts become isInstanceof[Type] and asInstanceof[Type]

I am not sure how to treat multiple ctors, as well as abstract methods, so I comment these out at the moment

it's not pretty, but the code is available publicly as a googlecode project; source at:

and you can checkout the code as:
svn checkout jatran

if you check it out, pls run the default ant build.xml file task (ant); it will compile and create the dist jar file. then run ./ for usage info

typical usage is: ./ -l scala -o ~/some/path/out -i src
- it defaults to scala, so you can omit "-l scala"
- if src is a folder it will parse the java files in it recursivly
- output folder will be created if it does not exist (defaults to ./jatran-out)

I have also added in an "untyped" option, which will strip type bit of a variable declaration, and keep only the identifier bit ie. var t:Type = foo becomes var t = foo
./ -u -o ~/some/path/out -i src

for Actionscript 2 & 3:
- it does the right thing with packages
- generally obeys the structure of as code (post-colon syntax, etc as above)
a few other things I can't remember, but check it out

the main application driver is written in groovy; it's a fun language, and I couldn't pass up using the commons-cli builder, plus groovy makes file processing a breeze :)

if you have suggestions, pls drop a line at eokyere_AT_gmail_DOT_com