Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the key semantic differences between Ruby and Javascript

If one were to implement Ruby on top of a Javascript engine (either in the browser or on top of standalone V8 or Spidermonkey), what would be the key impedance mismatches between the Ruby and JS object models ?

like image 547
Nick Main Avatar asked Apr 01 '11 15:04

Nick Main


1 Answers

The most in-your-face one is obviously the fact that ECMAScript is prototype-based and Ruby is class-plus-mixin-based. Also, in Ruby, encapsulation is done with objects, in ECMAScript with closures.

However, my guess is that Ruby's control flow constructs are going to be a much bigger hurdle than its object model. After all, James Coglan's JS.Class is basically an implementation of Ruby's object model in ECMAScript and it's not that big.

ECMAScript simply lacks the tools needed to build your own control-flow constructs on top of it. Typically, you need either GOTO, continuations or proper tail calls. If you have one of those, you can easily implement everything else: exceptions, loops, switches, threads, Fibers, generators, coroutines, … you name it.

But ECMAScript doesn't have them (and for good reason, at least in the case of GOTO). The only control-flow construct ECMAScript has that is powerful enough to be able to build other constructs on top of is exceptions. Unfortunately, those are pretty slow. (Nonetheless, they have been used as an implementation substrate, for example in the Microsoft Live Labs Volta compiler, which used ECMAScript exceptions to implement .NET exceptions, iterators, generators and even threads.)

So, basically you are stuck with implementing at least your own call stack if not an entire interpreter (as is the case with HotRuby), performing global CPS transforms or something like that.

Basically, what you want from a Ruby engine running on top of ECMAScript, is

  1. a faithful implementation of the RubySpec (specifically the control-flow constructs such as threads, fibers, throw/catch, exceptions etc.),
  2. performance and
  3. tight integration with ECMAScript (i.e. the ability to pass objects and call methods back and forth between the two languages).

Unfortunately, when you have to resort to tricks like managing your own stack, doing CPS transforms, building on top of exceptions, … it turns out that you can only pick two of the three goals.

like image 160
Jörg W Mittag Avatar answered Oct 20 '22 19:10

Jörg W Mittag