Details
-
New Feature
-
Status: Closed
-
Major
-
Resolution: Won't Fix
-
1.0-beta-4
-
None
-
None
Description
Since people are starting talking about adding macros etc to Groovy. I have quickly packed a poor man's experimental pre-processor here and would like to show that a simple and easy pre-processor can be done and achieve some nice functionality.
With groovy-pp, now I can do things like:
1. sqlG
fn
ln
id = 1
#sql [sql] {
select firstname, lastname
into :fn, :ln
from mytable
where emp_id = :id
}
#sql [sql] {
update thetable set firstname = :fn where emp_id = :id
}
":" is used to identify host variables. It's inspired by sqlJ.
More embedded SQL has yet to be implemented.
2. Make powerful JavaBeans :
class MyBean {
#boundsupport
#bound int balance = 0
#readonly name
#writeonly message
}
And then I can use Closure to listen to the propertyChangeEvent:
bean = new MyBena()
bean.addPropertyChangeListener {
print "${it.propertyName}, ${it.oldValue}, ${it.newValue}"
}
3. A beeper
Actually it's for quick dumping messages to stdout with the information of the current method, class, and line number in the source file:
#beepon
a = 1
1.times {
#beep "a has a value of ${a}"
#beep a has a value of :a
}
-O< PPBeepTest$1.doCall(PPBeepTest.groovy:7): a has a value of 1
-O< PPBeepTest$1.doCall(PPBeepTest.groovy:7): a has a value of 1
The beeper can be turned off quickly by
#beepoff
There is also a macro that saves me from typing excessive "\" in a regular expressions.
All the above is sampled by a file called
PPTest.groovy
in:
bran.groovy.preprocessing
Where all the source code can be found, including a configuration file that maps macro directives to processors. All these are hard-coded right now.
Basically I have added a filter to the InputStreamCharStream, which provides source stream to the lexer. All the macro expanding happens before the lexer.
I have used # as the indicator of possible pre-processing and it has to be the first none-space character on a line to take effect. I believe some people prefer other indicators such as @. We can easily change that later.
This stuff is very experimental and probably only good for demo purpose. But I like the light-weight nature that allows everyone to quickly hack Groovy. It's quite possible that the whole thing will be tossed out once we have a formal interface for language extension.
Personally I have found the JavaBeans macros are quite powerful together with use of Closures as listeners. Note that that indexed properties are not implemented yet.
I have made minor changes to InputStreamCharStream to open up the hook. One or two new methods have been created in the DefaultGroovyMethod, which are none-essential and nice to have. A little change is also made to the Sql class, but i don't think it's required to run the test script.
Gone for sleep