Having just finished the first full run through of a groovy pretty printer,
I thought I'd flex it's muscles by creating a useful command line program...
java2groovy [file ...]
Description:
The java2groovy tool reads class and interface definitions, written in the
Java programming language, and converts them into groovy source files.
to do this...
- I took the original java.g grammar which groovy.g is based upon
- amended it to remove Java features not implemented in groovy.g
("do" keyword, Array Initialisers etc)
- Created a Java2GroovyMain which takes Java files and parses into a
Java like source AST
- Converted the Java like source AST into a one for one Groovy equivalant
- Applied a Groovifier, which applies common simplification tasks to
the AST (e.g. don't need public keyword if you have other modifiers)
- Then the resultant groovy AST is output using the "pretty printer"
(not in subversion yet RC3? post 1.0?)
So... job done, what's next :-)
Seriously though...
- java.g needs to be amended some more to use create() instead of #[],
otherwise line/col nums are lost
- Groovifier.java is an interesting step, lots of tiny refactorings,
at the source AST level, very powerful...
//----
// (e.g. don't need public keyword if you have other modifiers)
//
if (t.getType() == MODIFIERS) {
GroovySourceAST publicNode = t.childOfType(LITERAL_public);
if (t.getNumberOfChildren() > 1 && publicNode != null) {
// has more than one modifier, and one of them is public
// delete 'public' node
publicNode.setType(EXPR);
}
//----
- some minor changes to things like string literals (get a double double-quote each time at mo...)
- all pretty printer issues apply (no comments on AST etc)
java2groovy is now included in Groovy 1.0 (download here)
(very very beta) NO DOCS, NO WARRANTIES etc etc
Oh yes... a sample...
$ java2groovy src/test/groovy/lang/MockWriter.java
/*
Automatically Converted from Java Source
by java2groovy v0.0.1 Copyright Jeremy Rayner 2007
!! NOT FIT FOR ANY PURPOSE !!
'java2groovy' cannot be used to convert one working program into another
*/
package groovy.lang
class MockWriter
{
private String output
String getOutput() {
String answer = output
output = null
return answer
}
void setOutput(String
output) {
}
void println() {
setOutput(""println()"")
}
void println(Object
object) {
setOutput(""println("" + object + "")"")
}
void print(Object
object) {
setOutput(""print("" + object + "")"")
}
}