The Mirah home page says
Mirah supports various mechanisms for compile-time metaprogramming and macros. Much of the “open class” feel of dynamic languages is possible 开发者_JAVA技巧in Mirah.
But I'm unable to find any specifics. Does anyone have further information?
Mirah supports compile time macros. With them, you can define functions that are run at compile time that modify the syntax tree. This allows you to simplify some of the common patterns you see in Java into ones more like those found in Ruby.
For example, times
is implemented as a macro--though it's currently written in Ruby, not Mirah.
You can use it like this
5.times do |i|
puts i
end
to print out the numbers 0-4
in Java it would look something like
for(int i=0;i < 5; i++) {
System.out.println(i);
}
You can of course define your own macros by using the macro def
macro. For example, say I want to use the common logger4j pattern of checking whether debug is enabled before constructing the debug string. With a macro, I could make the check implicit doing something like this:
macro def debug debug_input
quote do
if logger.debugEnabled
logger.debug `debug_input`
end
end
end
which I could call like this
debug "something low level is going on: " + gimme_all_the_bytes_as_a_string
what's going on there is I'm creating a piece of syntax tree with the quote do ... end
and dropping the "something low level is going on: " + gimme_all_the_bytes_as_a_string
expression into it using the ``s which in Mirah macro quote blocks, unquote the syntax tree node within them.
There currently aren't too many resources about how Mirah works, but you can look at the example code on Github. If you have more questions feel free to send an email to the mailing list.
精彩评论