Ruby Blocks / Closing Java in C

I tried to understand how Ruby blocks work, and for that I tried to implement them in C.

One easy way to implement closures is to pass void* to the enclosing stack for a closure / function, but Ruby blocks also handle return and break commands from the scope using that block.

 loop do break i if (i >= 4000) i *= 2 end 

I think one of the closure sentences for Java works the same way.

So, how would you implement Ruby blocks / Java closures in C?

+6
java c ruby
source share
3 answers

The concept of closures requires the concept of contexts. C is based on the stack and the CPU register, so to create a block / close you need to be able to manipulate the stack pointer in the correct (and re) way and save the storage / restore registers as needed.

The way interpreters or virtual machines do this is to have a context structure or something similar, and not use the stack and registers directly. This structure tracks the stack and, if necessary, some registers if you are developing a register-based virtual machine. At the very least, this is the easiest way to do this (although a little less efficient than actually displaying things correctly).

+10
source share

In fact, I did not realize anything, so take it with a bag of salt.

There are two parts to closing: the data environment and the code environment. As you said, you can probably pass a void * to handle data references. You can probably use setjmp and longjmp to implement non-linear control flow jumps that require a Ruby break.

If you want to close, you probably should program in a language that actually supports them. :-)

UPDATE: Interesting things are happening in Clang. They prototyped the closure for C. http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html may seem interesting.

+3
source share

There's a nice set of slides on Ruby Blocks as part of the Rails with Passion course:

Ruby_Blocks.pdf

This covers the presentation of the block, how they pass arguments and are executed, and even further into objects such as Proc objects. This is very clearly explained.

Then it may be interesting to see how the JRuby guys processed them when parsing them in Java. Take a look at the source at codehaus .

+2
source share

All Articles