How to parse Ruby Code using IronRuby?

219 Views Asked by At

I am new to IronRuby. I am trying to integrate it with C#.

I have created following example and it is working fine.

string rubyCode = @"
                    def function_111(test)
                       print 1
                    end                   
            ";
 ScriptEngine engine = Ruby.CreateEngine();            
 ScriptScope scope = engine.CreateScope();
 engine.Execute(rubyCode, scope);
 dynamic sayHelloFun = scope.GetVariable("function_111");
 sayHelloFun("test");

If you look at above code then I am using execute method that compile and execute code but instead of that I only want to parse code it means its syntax are correct or not.

How can that possible ?

1

There are 1 best solutions below

0
codekaizen On

The link posted appears dead, and the search engine cache copies appear to be rotting, so I'm going to scrape what is left of the post and interpret it below.


You can use IronRuby along with the Dynamic Language Runtime (DLR) to parse the Ruby code. The steps are to: create a Ruby engine instance, create a script source and unit, create a parser and parse to an AST, and walk the AST with a Walker.

Create the Engine

var runtime = IronRuby.Ruby.CreateRuntime();
var engine = runtime.GetEngine("rb");

Create the Source Unit

var src = engine.CreateScriptSourceFromString(@"puts 'hello'"); // also: engine.CreateScriptSourceFromFile
var srcUnit = HostingHelpers.GetSourceUnit(src);

Parse

var parser = new Parser();
var srcTreeUnit = parser.Parse(srcUnit, new RubyCompilerOptions(), ErrorSink.Default);

Walk the AST

var walker = new MyWalker();
walker.Walk(srcTreeUnit);

You'll need to subclass the Walker class, which has numerous virtual methods to handle visiting various nodes in the AST. The one used in the LinqPad Query looks like so:

public class MyWalker : Walker
{
    protected override void Walk(MethodCall node)
    {
        Console.WriteLine("Method call: " + node.MethodName);
        base.Walk(node);
    }

    protected override void Walk(StringLiteral node)
    {
       Console.WriteLine("String Literal: " + node.GetMutableString().ToString());
       base.Walk(node);
    }
}

When you run this walker on the AST generated above, you get the following:

Method call: puts
String Literal: hello

I used LinqPad and added the IronRuby 1.1.3 nuget package and created a LinqPad Query with the above.