"Nospam" <news.home.nl-1 / nospam.no-nonsense.org> schrieb im Newsbeitrag
news:cdgcqd$67n$1 / news3.tilbu1.nb.home.nl...
> Hi,
>
> Once in a while the question pops up if it is possible to compile Ruby
> code to native machine code. The answer has always been no. But I keep
> wondering how hard it would really be to make this possible.
>
> Ruby is written in C. And when Ruby parses a Ruby script it converts
> each statement to a C call. Probably the same calls you can use on your
> own in a Ruby C extension. So why wouldn't it be possible to parse a
> Ruby script and convert all statements to Ruby C code and put it in a
> *.c file (instead of calling the Ruby C statements directly). This *.c
> file can then be compiled into machine code with a C compiler like gcc.
> If each *.rb file is converted to a C file it could be compiled to a
> dynamically loadable library which could then be used on require
> statements (just like regular Ruby C extensions).
>
> What I mean is, this...
>
> class Example
>    def example
>      puts "Hello World!"
>    end
> end
>
> ... can also be written in C using the Ruby C API, am I right? So why
> wouldn't it be possible to convert all Ruby code to C code using the
> Ruby C API?

I guess it *is* possible, but then you would have to bundle gcc with the
Ruby interpreter, because you must deal with dynamic redefinition of
methods and eval.

> This would probably result in some performance gain (no need to parse
> the code anymore at run-time),

AFAIK at runtime there is a parse phase and an execute phase.  Each line
of code is only parsed once and then converted into some kind of byte code
(not the Java flavour), so you probably don't gain much time.

> but for some people more important, you
> can distribute your Ruby applications closed-source.

That would impose certain restrictions, especially you must forbid this:

# just a stupid example that loads different files
# depending on some runtime state
case some_var
  when "foo"
    require "x-as-foo-impl.rb"
  when "bar"
    require "x-as-bar-impl.rb"
  when /^(\w+)-\w+$/
    require "x-as-#{$1}-impl.rb"
  else
    require "x-default-impl.rb"
end

> In the future the
> performance gain maybe could be increased by performing special
> optimizations during the conversion process.
>
> Am I right on this, or do I forget something important which makes the
> above quite hard to do?

I think so, as noted above.

Regards

    robert