added a comment - - edited
is a local variable, so we won't be able to capture it and put into the binding, but:
will go in the binding of the script by default.
For methods, as if you evaluate this script:
def err(msg) { System.err.println(msg) }
you will have to introspect the Script class that is compiled to retrieve the methods that have been defined on it. Then, you wrap that in a MethodClosure that you keep inside the binding as 'err' (for the key), and the method closure for the value, so that later on, people can call err('hi') (in fact, the script will retrieve the err property in the binding, and as it's a closure, will call it)
The trickier thing is probably how to memorize the imports :-/
An idea could be to "catch" the imports as if they were shell commands, then you keep them somewhere in memory.
You could append them to the script evaluated, but you'd loose the right line number information.
So a better approach, ideally, would be to use the GroovyClassLoader and add imports transparentely when the script is compiled.
See blackdrag's blog for some ideas: http://blackdragsview.blogspot.com/2006/11/chitchat-with-groovy-compiler.html
This is also a technique that Alexandru Popescu used to add TestNG imports automatically in his Test'N'Groove project:
Look at the end of this file to see how to do that:
http://testngroove.googlecode.com/svn/trunk/src/main/org/codehaus/groovy/testng/GroovyTestNG.java
The last thing also that would be needed would be to remember class definitions, so that you can define a class in a first script:
and then in another script execution being able to create new instances:
There might be some tricks with classloaders to make that possible though, and I'm not sure yet how to best do that.
Perhaps Jochen can give some perspective on this.
Requirements: