Category Archives: Ruby

RuScript, Ruby Interpreter in JavaScript (1) The Project

When I have free time, I’m working on:

I’m writing the code following the TDD (Test-Driven Development) workflow (see commit history)

The idea is to have a Ruby interpreter written in JavaScript, so it can run at the browser, or at the server with Node.js. I’m not implementing a compiler yet, because I want to do “baby steps”, and because Ruby semantic could be different to JavaScript one. Ie, the resolution of methods, or check if a variable is local to a function or not, are examples of divergences between the languages. So, I decided to write an interpreter.

I’m applying “dog fooding”: the parser is written using:

I’m applying SimpleGrammar in other projects, like RustScript. There is an implementation in C#, too, named GrammGen). A fragment of the defined rules for RuScript parser:

// Expression Level 1
get('Expression1', 'Plus', 'Expression0')
    .generate('Expression1', function (values) { return new AddExpression(values[0], values[2]); }),
get('Expression1', 'Minus', 'Expression0')
    .generate('Expression1', function (values) { return new SubtractExpression(values[0], values[2]); }),

// Expression Level 0
get('Expression0', 'Multiply', 'Term')
    .generate('Expression0', function (values) { return new MultiplyExpression(values[0], values[2]); }),
get('Expression0', 'Divide', 'Term')
    .generate('Expression0', function (values) { return new DivideExpression(values[0], values[2]); }),

// Term
get('Term', 'LeftBracket', 'ExpressionList', 'RightBracket')
    .generate('Term', function (values) { return new IndexedExpression(values[0], values[2]); }),
get('@@', 'Name').generate('ClassVariable', 
    function (values) { return new ClassVariableExpression(values[1].getName()); }),
get('@', 'Name').generate('InstanceVariable', 
    function (values) { return new InstanceVariableExpression(values[1].getName()); }),
get('LeftParenthesis', 'Expression', 'RightParenthesis')
    .generate('Expression0', function (values) { return values[1]; }),
get('LeftBracket', 'RightBracket')
    .generate('Array', function (values) { return new ArrayExpression([]); }),
get('LeftBracket', 'ExpressionList', 'RightBracket')
    .generate('Array', function (values) { return new ArrayExpression(values[1]); }),

For each discovered element, the grammar is building an expression, that can be evaluate using a context. A context has the values of the visible variables. Example:

function NameExpression(name) {
    this.evaluate = function (context) {
        var value = context.getValue(name);
        if (typeof value == 'function')
            return value();
        return value;
    this.getName = function () { return name; };
    this.setValue = function (context, value) {
        context.setLocalValue(name, value);

function InstanceVariableExpression(name) {
    this.evaluate = function (context) {
        if (!context.$self.$vars)
            return null;
        return context.$self.$vars[name];
    this.getName = function () { return name; };
    this.setValue = function (context, value) {
        if (!context.$self.$vars)
            context.$self.$vars = { };
        context.$self.$vars[name] = value;

function ClassVariableExpression(name) {
    this.evaluate = function (context) {
        if (!context.$self.$class.$vars)
            return null;
        return context.$self.$class.$vars[name];
    this.getName = function () { return name; };
    this.setValue = function (context, value) {
        if (!context.$self.$class.$vars)
            context.$self.$class.$vars = { };
        context.$self.$class.$vars[name] = value;

function ConstantExpression(value) {
    this.evaluate = function () {
        return value;

I have access to JavaScript features from Ruby, example, a test:

exports['Evaluate JavaScript global name'] = function (test) {
    global.myglobal = 42;
    var context = contexts.createContext();
    var parser = parsers.createParser("js.myglobal");
    //parser.options({ log: true });
    var expr = parser.parse("Expression");
    var result = expr.value.evaluate(context);
    test.equal(result, 42);

The js namespaces allowed the access to JavaScript defined variables, and all its ecosystem, at the browser or at the server.

I want to share my advances at RubyConf 2014 Argentina.

Next steps: access to Node.js require, web site examples using Node.js/Express, console examples, browser examples, etc.

Stay tuned!

Angel “Java” Lopez

RubySharp, implementing Ruby in C# (3)

Previous Post

In RubySharp, we can define new functions (methods of the current object), and invoke them. There are some built-in functions in C#:

Every function should implement the interface:

public interface IFunction
    object Apply(DynamicObject self, Context context, IList<object> values);

On apply, each function receives the object (self), the context for variables (locals, arguments, closure….), and a list of already evaluated arguments.

An example, the implemention of puts:

public class PutsFunction : IFunction
    private TextWriter writer;

    public PutsFunction(TextWriter writer)
        this.writer = writer;

    public object Apply(DynamicObject self, Context context, IList<object> values)
        foreach (var value in values)

        return null;

It receives the object to which it is a method, the context, and a list of arguments. Each of the arguments was evaluated. The implementation simply sends the arguments to a TextWriter, one argument per line. The TextWriter is provided when the function object is created (in the Machine object, that represents the current running environment). This injected facilites the test of the function, example:

public void PutsTwoIntegers()
    StringWriter writer = new StringWriter();
    PutsFunction function = new PutsFunction(writer);

    Assert.IsNull(function.Apply(null, null, new object[] { 123, 456 }));

    Assert.AreEqual("123\r\n456\r\n", writer.ToString());

The above code was born using the TDD workflow.

Let’s see another built-in function, require:

public class RequireFunction : IFunction
    private Machine machine;

    public RequireFunction(Machine machine)
        this.machine = machine;

    public object Apply(DynamicObject self, Context context, IList<object> values)
        string filename = (string)values[0];
        return this.machine.RequireFile(filename);

This time, the job of loading a file is delegated to the Machin object, injected in the constructor.

And finally, let’s review the code of a defined function (defined in RubySharp):

public class DefinedFunction : IFunction
    private IExpression body;
    private IList<string> parameters;
    private Context context;

    public DefinedFunction(IExpression body, IList<string> parameters, Context context)
        this.body = body;
        this.context = context;
        this.parameters = parameters;

    public object Apply(DynamicObject self, Context context, IList<object> values)
        Context newcontext = new Context(self, this.context);

        int k = 0;
        int cv = values.Count;

        foreach (var parameter in this.parameters) 
            newcontext.SetLocalValue(parameter, values[k]);

        return this.body.Evaluate(newcontext);

In this case, a new contexts is built, containing the new arguments to the defined function, but with the original closure, injected in the constructor. The context provided in the Apply is not used.

Next topics: some command implementations, the Machine object, the REPL, etc…

Stay tuned!

Angel “Java” Lopez

End Of Iteration 2014w14

Previous Post
Next Post

Code Generation

I updated my template engine in JavaScript, with a minor change to skip new lines in some contexts:

Then I consumed the new version in AjGenesis for Node:

I published the first version of my Sinatra code generation tasks and templates:

The simple generated site can manage list of entities, persisted using sqlite3 and data-mapper.

I removed bower from my Express code generation tasks and templates:

because I think it is more clear to have directly the assets in the repository, instead of installing via bower.

And I updated my Php tasks and templates:

so now it is using a first page with Bootstrap.


I wrote a simple library to support complex number operations in JavaScript

As usual, I wrote the code using TDD workflow. You can check the commit history.

Learning Node.js

I updated my

with a simple sample of a web server. I recorded a Google Hangout (see Spanish post)


Additionally, I started new code kata in JavaScript,

I did a minor internal refactor in ScalaSharp my Scala interpreter in C#.

I added a do operation to my simple asynchronous library. The do operation launch a “parallel” function. You can chain do operations, to launch more than one operation. The next then or map operation will receive the result of the do operations as elements in an array, after full completion of the “launched” functions. Usually, those functions perform asynchronous calls.

I was working in two non-public projects, too.

More fun is coming.

Keep tuned!

Angel “Java” Lopez

New Month’s Resolutions: April 2014

Review of my March’s resolutions:

– Work on DictSharp [complete] see repo
– Give talk about Node.js Distributed Applications [complete] see repo see online slides
– Improve SimpleGammon [complete] see repo
– Improve Annalisa [complete] see repo
– Add @for to Templie [pending]
– Work on PreciosaAnnalisa online web services [complete] see repo
– Improve my Node.js Distributes Applications samples [complete] see repo see repo see repo
– Work on ScalaSharp [complete] see repo
– Improve ClojSharp [complete] see repo
– Improve SimpleAsync, do operation (functions in parallel) [pending]
– Improve Aktores [pending]
– Distributed messages in AjErl [pending]
– Add variable scope to Mass language [pending]
– Start code generation as a service [partial]

Additionally, I worked on:

– Complexo, simple complex numbers operations in JavaScript [complete] see repo
– Started RustScript, a Rust programming language interpreter in JavaScript [complete] see repo
– Continue RuScript, a Ruby interpreter in JavaScript [complete] see repo
– Continue RubySharp, a Ruby interpreter in C# [complete] see repo
– Started AjLispScala, a Lisp interpreter in Scala, using TDD and SBT [complete] see repo
– Recorded a second video Node.js Spanish tutorial [complete] see post

For this new month, my resolutions are:

– Continue AjLispScala
– Continue AjGenesisNode-Express
– Continue AjGenesisNode-PHP
– Continue RuScript
– Continue RustScript
– Distributed Messages in AjErl
– Give a talk Intro to Node.js
– Publish a new Node.js video tutorial

More fun is coming.

Keep tuned!

Angel “Java” Lopez

End Of Iteration 2014w12

Previous Post
Next Post

Ruby Interpreters

I updated my projects

The first in a Ruby interpreter in C#. I started to add the support to detect the local variables in an scope. In Ruby, there is the function local_variables() that returns a list of the names of local declared variables (not only the already initialized).

The second project is the seed to my next talk: it implements Ruby in JavaScript, as an interpreter. I added more support for modules and classes, and function declaration with and without arguments and parenthesis. I’m using my grammar/parser generation:

It was updated to support new use cases (dog fooding!).


I added some simple features to

My Rust Programming Language interpreter in JavaScript. Not, it has function definition with arguments, let and let mut (mutable), some new arithmetic, bitwise and logical operators, with precedence. And a powerful assert! to start writing test programs.


I updated

My Scala interpreter in C#. The additions were simple: more node support. A node is the product of a parser, and define a part of the program. It has a type to be checked. That is the main difference with expression: a node has a type that can be inferred from the rest of the program, or by explicit declaration. As a typed language, an Scala interpreter cannot directly evaluate expression. I should check the types of the nodes, and THEN, generate a correct expression tree.

Code generation

I created

A new global tasks to be used by AjGenesis and related tasks to modify the model using command line. I started the new global tasks

to generate code for PHP and Django. There are only the skeletons, but I want to generate code for these languages/frameworks using a free model. Meanwhile, you can check the simple pages generated from:

The next big step: having a code-as-a-service application, written in Node.js, using AjGenesisNode, and deployed on Heroku.

I worked on two non-public projects, too.

More fun is coming!

Keep tuned!

Angel “Java” Lopez

Ruby: Links, News And Resources (7)

Previous Post

Ruby for Kids

Composition Of Responsibility vs Interface Implementation

Python vs PHP vs Ruby

Dando los primero pasos en Ruby

Try Ruby

Episode 2 – All The Cool Kids Use Ruby

Shoes is a cross-platform toolkit for writing graphical apps easily and artfully using Ruby.

monkeybars / monkeybars-core
MVC GUI framework using JRuby and Swing

Rawr, a packaging and deployment tool, is all you’ll ever need for your JRuby projects. With Rawr, a simple, pre-generated configuration file turns your code into an executable jar, a .exe for Windows, and a .app for OS X.

Swing with JRuby: Developing a Desktop Application with the JRuby and Java Swing APIs

It creates a skelton .rb file from a .glade file.

Screencast: Coding Conway’s Game of Life in Ruby the TDD Way with RSpec

Shoes Roundup: Ruby GUI App Development Goodness

Rack (web server interface)

Fast, concurrent ruby web applications with EventMachine and EM::Synchrony

Integrate Shoes into Aptana Studio RadRails

Rack App from Scratch

rdebug Cheat Sheet

Intro to OWIN and Knack

My Links

Keep tuned!

Angel “Java” Lopez

New Month’s Resolutions: December 2013

Review of my November’s resolutions:

This new month’s resolution:

– Start compiler reduced Python to C, using JavaScript [complete] repo
– Give a talk about Ruby in C# [complete] slides repo
– Start Ruby to JavaScript compiler [complete] repo
– Complete variable scope in Mass language [pending]
– Give a talk about compiling languages to JavaScript [complete] slides
– Write web framework for AjTalkJs (to be used in Node.js) (plain? MVC?) [pending]
– Improve NPM modules in AjTalkJs and AjTalk [partial] repo
– Improve unit test support in AjTalkjs and AjTalk [partial] repo
– Improve match and data structure in AjErl [pending]

My December’s resolutions:

– Give a one-day Node.js course
– Refactor and improve CobolScript
– Continue writing Ruby to JavaScript compiler
– Variable scope in Mass language
– More modules in AjTalkJs

More fun is coming ;-)

Keep tuned!

Angel “Java” Lopez

End Of Iteration 2013w48

Previous Post 
Next Post

Talk about Implementing Ruby

I gave a talk at RubyConf Argentina 2013, about implementing Ruby. Slides source at:

To be viewed online at:

It mentioned my work on RubySharp

my Ruby interpreter written in C#. Now, it can access native types and objects, requiring .rb modules or native .dlls.

My Apps

I updated the repo of my dynamic apps application (Node.js)

I should add MongoDB as first persistence implementation.


I published 0.0.3 version:

The new feature: a “peek” function, to look at the next token, without removing it.

I added the new feature to grammar (my Ruby interpreter in JavaScript).

Other works:

– Update SimpleYaml to support real numbers

– Test refactor of CobolScript

– Update ClojScript to Visual Studio 2010

And I was working on two non-public projects.

This new week will be dedicated to some JavaScript projects and ideas, and to give a one-day course of Node.js

Keep tuned!

Angel “Java” Lopez

TDD Rocks! (6) Playing with Ruby

Previous Post
Previous Post with Ruby

I’m still learning Ruby. To practice the language, I’m writing a Tokenizer using my TDD (Test-Driven Development) workflow.

A new video at

I did two redesigns:

– To provide the text to tokenize in the tokenizer constructor

– Rename getTokens methods to a more "rubyist” name get_tokens

After those redesigns, I dived into a big implementation refactor. Maybe, I had to avoid that work, or split it in more manageable pieces. At the end, I survived, and the tokenizer implementation is started to emerge. You can check another of my implementations, in JavaScript/NodeJs:

The Ruby version is at:

Keep tuned!

Angel “Java” Lopez

End Of Iteration 2013w47

Previous Post
Next Post

Implementing Ruby

My main outcome is my work on implementing Ruby, using C#:

I implemented:

– Access to native types and objects
– Modules
– Classes
– Nested modules and classes
– Require of Ruby programs
– Require of native dlls
– Singleton class
– Examples (console, win forms, http)

I will present this work this week, at RubyConf Argentina 2013

Implementing Ruby in JavaScript

I started a new implementation, this time in JavaScript

It is still work in progress. I’m using SimpleGrammar for the parser/lexer, but I should review this path. Ruby syntax has some quirks to tackle.

Other works:

– Refactor of CobolScript:
– Work on three non-public projects

Keep tuned!

Angel “Java” Lopez