<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Tomáš Matoušek's Weblog</title>
	<atom:link href="http://matousek.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://matousek.wordpress.com</link>
	<description>IronRuby, DLR, .NET Framework</description>
	<lastBuildDate>Sun, 11 Dec 2011 19:50:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='matousek.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/545371f672fc051653bf088e1b9b73ec?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Tomáš Matoušek's Weblog</title>
		<link>http://matousek.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://matousek.wordpress.com/osd.xml" title="Tomáš Matoušek&#039;s Weblog" />
	<atom:link rel='hub' href='http://matousek.wordpress.com/?pushpress=hub'/>
		<item>
		<title>IronRuby on Your Phone</title>
		<link>http://matousek.wordpress.com/2010/03/21/ironruby-on-your-phone/</link>
		<comments>http://matousek.wordpress.com/2010/03/21/ironruby-on-your-phone/#comments</comments>
		<pubDate>Mon, 22 Mar 2010 05:30:31 +0000</pubDate>
		<dc:creator>tomasmatousek</dc:creator>
				<category><![CDATA[DLR]]></category>
		<category><![CDATA[IronRuby]]></category>
		<category><![CDATA[Compact Framework]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://matousek.wordpress.com/?p=79</guid>
		<description><![CDATA[Windows Phone 7 application platform was finally revealed at MIX10. It generated a lot of excitement among .NET developers presumably due to the fact that it’s based on Silverlight. No need to learn a completely new programming model or libraries. Since the .NET Framework supports many languages you might wonder if you have the same [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=79&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Windows Phone 7 application platform was finally revealed at <a href="http://live.visitmix.com/MIX10/Sessions/CL18" target="_blank">MIX10</a>. It generated a lot of excitement among .NET developers presumably due to the fact that it’s based on Silverlight. No need to learn a completely new programming model or libraries. Since the .NET Framework supports many languages you might wonder if you have the same choice on the Phone. In particular, could you script the Phone using languages built on <a href="http://www.codeplex.com/dlr" target="_blank">Dynamic Language Runtime</a>? I’m excited to announce that <strong><a href="http://ironruby.codeplex.com/releases/view/41854" target="_blank">IronRuby 1.0 RC4</a> works on Windows Phone 7</strong>! Although there are some limitations the basic scripting just works as you’d expect. But keep in mind that the platform is still a technology preview (CTP) so not all features need to work seamlessly. Let’s dig into details.</p>
<h3>Limitations</h3>
<p>First of all, why are there any limitations at all if the Phone’s platform is Silverlight and IronRuby works on Silverlight since its inception? Although the UI and Media APIs are pretty much the same the Phone differs from the browser plug-in in the CLR execution engine and the Base Class Library. The Phone uses <em>Compact Framework</em> (CF) which provides only a subset of functionality available in the browser. The two platforms should converge in the future and the limitations will hopefully go away.</p>
<p>The main feature missing from the CF is <em>Reflection.Emit</em>. There are other differences but this is the most important one concerning dynamic languages. As you can imagine we do emit some code at runtime to implement dynamic features of our languages. However we also have an interpreter around. Each DLR based language can choose when to use the interpreter and when the compiler. Both IronRuby and IronPython interpret user code that is executed only a few times. It’s not efficient to compile such code since the cost for doing so is high and the execution throughput is not important. On the other hand code that’s running many times should be compiled and optimized. If the interpreter finds out that a function or a loop body is being executed more than <em>N</em> times it spawns its asynchronous background compilation. When the compilation is done the instructions that call the function or enter the loop are replaced by new ones that jump to the compiled code. The threshold <em>N</em> is configurable.</p>
<p>It should be clear now how to work around the lack of <em>Reflection.Emit</em> on the Phone. Let’s just interpret all the time! And indeed it mostly works. You won’t get a great throughput performance out of it but it works just fine for common scripts. Since the CLR interop is still available you can write performance critical code in C# and call it from the scripts. There are only a few CLR features that you need to avoid since the current interpreter doesn’t handle them without resorting to <em>Reflection.Emit</em>. The most significant are calls to methods with <em>out</em> or <em>ref </em>parameters. You also won’t be able to inherit a Ruby class from a CLR class or implement a CLR interface since that requires us to emit a proper CLR type. We are going to address both of these limitations in future versions.</p>
<p>So, IronRuby runs on the Phone. Why IronPython doesn’t yet? There is no technical reason why it couldn’t. Some parts of the IronPython runtime were just written before we implemented the interpreter and thus need some refactoring to enable full interpretation. You can motivate us to do the work faster by voting on <a href="http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=26534" target="_blank">CodePlex</a>.</p>
<h3>Sample App</h3>
<p>Let&#8217;s write an app that hosts IronRuby on the Phone. It’s really simple! You just use the DLR <a href="http://dlr.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=97301" target="_blank">Hosting APIs</a> as you would do when embedding a DLR scripting language in a Silverlight app. I’ll show only the interesting parts of the app. You can download the full source code <a href="http://github.com/tmat/blog/raw/master/ironruby-on-your-phone/PhoneScripter.zip" target="_blank">here</a>. You’ll need <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2338b5d1-79d8-46af-b828-380b0f854203&amp;displaylang=en" target="_blank">Visual Studio 2010 for Windows Phone CTP</a> and <a href="http://ironruby.codeplex.com/releases/view/41854#DownloadId=112345" target="_blank">IronRuby 1.0 RC4</a> to try it out. Install them both and then open PhoneScripter.sln, build the solution and deploy to the emulator. Make sure that references to IronRuby and DLR assemblies in the project are correct.</p>
<p>The few lines that you need to run a Ruby script in the Phone emulator (and hopefully on the real device when available) are:</p>
<ul>
<li>
<pre>_engine = Ruby.CreateEngine((setup) =&gt; { setup.Options[<span style="color:#800000;">"CompilationThreshold"</span>] = Int32.MaxValue; });</pre>
<p>Creates a Ruby engine that never compiles the interpreted code. I guess IronRuby could max out the compilation threshold by default when running on the Compact Framework. For now you need to do this manually.</li>
<li>
<pre>_engine.Runtime.LoadAssembly(<span style="color:#0000ff;">typeof</span>(Color).Assembly);</pre>
<p>Loads <em>System.Windows</em> assembly into the dynamic runtime so that we can script the UI. <em>System</em> and <em>mscorlib</em> assemblies are loaded by default.</li>
<li>
<pre>RubyContext context = (RubyContext)HostingHelpers.GetLanguageContext(_engine);
context.ObjectClass.SetConstant(<span style="color:#800000;">"Phone"</span>, <span style="color:#0000ff;">this</span>);</pre>
<p>Makes the <em>MainPage</em> class instance (<em>this</em>) available to the script via a global constant <em>Phone</em>. We’ll use it to access UI elements on the page. This is a hack! You should use ScriptScope Hosting API to expose host objects to the script in your .NET apps. However, the scope dynamic object internally uses methods with <em>out</em> parameters and we can&#8217;t interpret calls to it from Ruby. We&#8217;ll enable this in future. For now, we work it around by directly accessing IronRuby&#8217;s RubyContext class. Be aware that this class is not a part of the Hosting APIs, we might change it in future versions and break your code. So do not use it in any production code.</li>
<li>
<pre>MemoryStream stream = <span style="color:#0000ff;">new</span> MemoryStream();
_engine.Runtime.IO.SetOutput(stream, Encoding.UTF8);

<span style="color:#0000ff;">try</span> {
    <span style="color:#0000ff;">try</span> {
        _engine.Execute(Input.Text);
    } <span style="color:#0000ff;">finally</span> {
        <span style="color:#0000ff;">byte</span>[] bytes = stream.ToArray();
        Output.Text += Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    }
} <span style="color:#0000ff;">catch</span> (Exception ex) {
    Output.Text += ex.Message;
}</pre>
<p>Executes a script entered in <em>Input </em>TextBox, captures its output and appends it to the content of <em>Output</em> TextBox.</li>
</ul>
<p>We can now enter and run a Ruby script:</p>
<p><a href="http://matousek.files.wordpress.com/2010/03/phonescripter.png"><img style="display:block;float:none;margin-left:auto;margin-right:auto;border-width:0;" title="PhoneScripter" src="http://matousek.files.wordpress.com/2010/03/phonescripter_thumb.png?w=436&#038;h=766" border="0" alt="PhoneScripter" width="436" height="766" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matousek.wordpress.com/79/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/matousek.wordpress.com/79/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=79&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://matousek.wordpress.com/2010/03/21/ironruby-on-your-phone/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb51033949ffccd982ae32c9f890f25a?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">tomasmatousek</media:title>
		</media:content>

		<media:content url="http://matousek.files.wordpress.com/2010/03/phonescripter_thumb.png" medium="image">
			<media:title type="html">PhoneScripter</media:title>
		</media:content>
	</item>
		<item>
		<title>Forwarding meta-object</title>
		<link>http://matousek.wordpress.com/2009/11/07/forwarding-meta-object/</link>
		<comments>http://matousek.wordpress.com/2009/11/07/forwarding-meta-object/#comments</comments>
		<pubDate>Sat, 07 Nov 2009 22:03:53 +0000</pubDate>
		<dc:creator>tomasmatousek</dc:creator>
				<category><![CDATA[DLR]]></category>
		<category><![CDATA[DynamicMetaObject]]></category>
		<category><![CDATA[DynamicObject]]></category>
		<category><![CDATA[forwarding]]></category>
		<category><![CDATA[IDynamicMetaObjectProvider]]></category>

		<guid isPermaLink="false">http://matousek.wordpress.com/?p=59</guid>
		<description><![CDATA[The Dynamic Language Runtime (DLR) allows us to add dynamic behavior to .NET classes. Writing your own dynamic class, i.e. a class implementing IDynamicMetaObjectProvider interface, might be as easy as inheriting from System.Dynamic.DynamicObject. Or you might need more control over the dynamic operations and implement the IDynamicMetaObjectProvider interface manually. Or maybe you already have an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=59&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <em>Dynamic Language Runtime</em> (DLR) allows us to add dynamic behavior to .NET classes. Writing your own dynamic class, i.e. a class implementing <em>IDynamicMetaObjectProvider</em> interface, might be as easy as inheriting from <em>System.Dynamic.DynamicObject</em>. Or you might need more control over the dynamic operations and implement the <em>IDynamicMetaObjectProvider</em> interface manually. Or maybe you already have an existing class and need to add dynamic behavior while preserving its parent class. And perhaps you already have a class that implements <em>IDynamicMetaObjectProvider</em>, find this implementation useful and want to reuse it. What code do we need to write to achieve that?</p>
<p>The <em>ForwardingMetaObject</em> class defined below makes it easy to forward dynamic operations from one dynamic class (forwarder) to another (forwardee). </p>
<pre><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">sealed</span> <span style="color:#0000ff;">class</span> ForwardingMetaObject : DynamicMetaObject {
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">readonly</span> DynamicMetaObject _metaForwardee;

    <span style="color:#0000ff;">public</span> ForwardingMetaObject(Expression expression, BindingRestrictions restrictions, <span style="color:#0000ff;">object</span> forwarder, 
        IDynamicMetaObjectProvider forwardee, Func&lt;Expression, Expression&gt; forwardeeGetter)
        : <span style="color:#0000ff;">base</span>(expression, restrictions, forwarder) { 
       
        <span style="color:#008000;">// We'll use forwardee's meta-object to bind dynamic operations.</span>
        _metaForwardee = forwardee.GetMetaObject(
            forwardeeGetter(
                Expression.Convert(expression, forwarder.GetType())   <span style="color:#008000;">// [1]</span>
            )
        );      
    }

    <span style="color:#008000;">// Restricts the target object's type to TForwarder. </span>
    <span style="color:#008000;">// The meta-object we are forwarding to assumes that it gets an instance of TForwarder (see [1]).</span> 
    <span style="color:#008000;">// We need to ensure that the assumption holds.</span>
    <span style="color:#0000ff;">private</span> DynamicMetaObject AddRestrictions(DynamicMetaObject result) {
        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> DynamicMetaObject(
           result.Expression,
           BindingRestrictions.GetTypeRestriction(Expression, Value.GetType()).Merge(result.Restrictions),
           _metaForwardee.Value
       );
    }

    <span style="color:#008000;">// Forward all dynamic operations or some of them as needed //</span>

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> DynamicMetaObject BindGetMember(GetMemberBinder binder) {
        <span style="color:#0000ff;">return</span> AddRestrictions(_metaForwardee.BindGetMember(binder));
    }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
        <span style="color:#0000ff;">return</span> AddRestrictions(_metaForwardee.BindInvokeMember(binder, args));
    }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> DynamicMetaObject BindConvert(ConvertBinder binder) {
        <span style="color:#0000ff;">return</span> AddRestrictions(_metaForwardee.BindConvert(binder));
    }

    <span style="color:#008000;">// ... //</span>
}</pre>
<p>Let&#8217;s use this class in an example. Let&#8217;s define some class <em>B</em> simply as a subclass of <em>DynamicObject</em> that supports <em>GetMember</em>, <em>InvokeMember</em> and <em>Convert</em> <em>to String </em>dynamic operations: </p>
<pre class="csharpcode"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> B : DynamicObject {
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">readonly</span> <span style="color:#0000ff;">string</span> _name;

    <span style="color:#0000ff;">public</span> B(<span style="color:#0000ff;">string</span> name) {
        _name = name;
    }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">bool</span> TryGetMember(GetMemberBinder binder, <span style="color:#0000ff;">out</span> <span style="color:#0000ff;">object</span> result) {
        result = <span style="color:#006080;">&quot;got member &quot;</span> + _name + <span style="color:#006080;">&quot;.&quot;</span> + binder.Name;
        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">true</span>;
    }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">bool</span> TryInvokeMember(InvokeMemberBinder binder, <span style="color:#0000ff;">object</span>[] args, <span style="color:#0000ff;">out</span> <span style="color:#0000ff;">object</span> result) {
        result = <span style="color:#006080;">&quot;invoked member &quot;</span> + _name + <span style="color:#006080;">&quot;.&quot;</span> + binder.Name;
        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">true</span>;
    }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> <span style="color:#0000ff;">bool</span> TryConvert(ConvertBinder binder, <span style="color:#0000ff;">out</span> <span style="color:#0000ff;">object</span> result) {
        <span style="color:#0000ff;">if</span> (binder.Type == <span style="color:#0000ff;">typeof</span>(<span style="color:#0000ff;">string</span>)) {
            result = _name;
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">true</span>;
        } <span style="color:#0000ff;">else</span> {
            result = <span style="color:#0000ff;">null</span>;
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">false</span>;
        }
    }
}</pre>
<p>And now let&#8217;s define a class <em>A</em> that forwards these operations to <em>B</em> via <em>ForwardingMetaObject</em>: </p>
<pre><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> A : IDynamicMetaObjectProvider {
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">readonly</span> B _b;
    <span style="color:#0000ff;">public</span> B B { <span style="color:#0000ff;">get </span>{ <span style="color:#0000ff;">return</span> _b; } }

    <span style="color:#0000ff;">public</span> A(B b) {
        _b = b;
    }

    DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> ForwardingMetaObject(parameter, BindingRestrictions.Empty, <span style="color:#0000ff;">this</span>, _b, 
            <span style="color:#008000;">// B's meta-object needs to know where to find the instance of B it is operating on.</span>
            <span style="color:#008000;">// Assuming that an instance of A is passed to the 'parameter' expression</span>
            <span style="color:#008000;">// we get the corresponding instance of B by reading the &quot;B&quot; property.</span>
            exprA =&gt; Expression.Property(exprA, <span style="color:#006080;">&quot;B&quot;</span>)
        );
    }
}</pre>
<p>Finally, let&#8217;s run some C# 4.0 code that shows how it all works together: </p>
<pre><span style="color:#0000ff;">class</span> Program {
    <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main(<span style="color:#0000ff;">string</span>[] args) {
        B b1 = <span style="color:#0000ff;">new</span> B(<span style="color:#006080;">&quot;b1&quot;</span>);
        B b2 = <span style="color:#0000ff;">new</span> B(<span style="color:#006080;">&quot;b2&quot;</span>);

        <span style="color:#0000ff;">dynamic </span>a1 = <span style="color:#0000ff;">new</span> A(b1);
        <span style="color:#0000ff;">dynamic</span> a2 = <span style="color:#0000ff;">new</span> A(b2);

        Console.WriteLine(a1.SomeMember);
        Console.WriteLine(a2.SomeMember);
        Console.WriteLine(a1.SomeMethodCall());
        Console.WriteLine(a1.OtherMethodCall());
        Console.WriteLine((<span style="color:#0000ff;">string</span>)a1);
    }
}</pre>
<p>Output:</p>
<pre>got member b1.SomeMember
got member b2.SomeMember
invoked member b1.SomeMethodCall
invoked member b1.OtherMethodCall
b1</pre>
<p>The really great thing about DLR is that your dynamic objects will also work in IronRuby and IronPython even though you haven’t thought about it at all when authoring them. Assuming that we compiled the above code into <em>MyDynamicLibrary.dll</em> we can run IronRuby REPL and check it out:</p>
<pre>IronRuby 0.9.1.0 on .NET 4.0.20915.0
Copyright (c) Microsoft Corporation. All rights reserved.

&gt;&gt;&gt; require 'MyDynamicLibrary.dll'
=&gt; true
&gt;&gt;&gt; b1, b2 = B.new('[b1 in Ruby]'), B.new('[b2 in Ruby]')
=&gt; [B, B]
&gt;&gt;&gt; a1, a2 = A.new(b1), A.new(b2)
=&gt; [B, B]
&gt;&gt;&gt; a1.SomeMethodCall
=&gt; 'invoked member [b1 in Ruby].SomeMethodCall'
&gt;&gt;&gt; a2.OtherMethodCall
=&gt; 'invoked member [b2 in Ruby].OtherMethodCall'
&gt;&gt;&gt; a1.to_s                             # invokes ToString
=&gt; &quot;B&quot;                                   
&gt;&gt;&gt; a1.to_str                           # invokes dynamic to string conversion
=&gt; &quot;[b1 in Ruby]&quot;</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matousek.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/matousek.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=59&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://matousek.wordpress.com/2009/11/07/forwarding-meta-object/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb51033949ffccd982ae32c9f890f25a?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">tomasmatousek</media:title>
		</media:content>
	</item>
		<item>
		<title>Python says hello to Ruby</title>
		<link>http://matousek.wordpress.com/2009/04/15/python-says-hello-to-ruby/</link>
		<comments>http://matousek.wordpress.com/2009/04/15/python-says-hello-to-ruby/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 04:39:00 +0000</pubDate>
		<dc:creator>tomasmatousek</dc:creator>
				<category><![CDATA[IronRuby]]></category>
		<category><![CDATA[IronPython]]></category>
		<category><![CDATA[REPL]]></category>

		<guid isPermaLink="false">http://matousek.wordpress.com/2009/04/15/python-says-hello-to-ruby/</guid>
		<description><![CDATA[Today we&#8217;re going to finish our REPL that we started a couple of posts ago. We&#8217;ll add support for switching among available DLR languages and for execution of multi-line snippets of code. We&#8217;ll then use the REPL to show how IronPython and IronRuby can interact with each other. Let&#8217;s get right to the final REPL [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=50&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Today we&#8217;re going to finish our REPL that we started a couple of posts ago. We&#8217;ll add support for switching among available DLR languages and for execution of multi-line snippets of code. We&#8217;ll then use the REPL to show how IronPython and IronRuby can interact with each other.</p>
<p>Let&#8217;s get right to the final REPL code:</p>
<pre><span style="color:green;"># github: <a href="http://github.com/tmat/blog/blob/master/multilingual-repl/repl.rb" target="_blank">repl.rb</a></span>
load_assembly 'Microsoft.Scripting'
Hosting = Microsoft::Scripting::Hosting
Scripting = Microsoft::Scripting

class REPL
  def initialize
    @engine = IronRuby.create_engine
    @scope = @engine.create_scope
    @exception_service = @engine.method(:get_service).of(Hosting::ExceptionOperations).call
    @language = "rb"
  end

  def run
    while true  
      print "#@language&gt; "
      line = gets
      break if line.nil?

      if line[0] == ?#
        execute_command line[1..-1].rstrip 
      else
        execute_code read_code(line)
      end
    end
  end
  
  # Reads lines from standard input until a complete or invalid code snippet is entered.
  # Returns ScriptSource that represents an interactive code.
  def read_code first_line
    code = first_line
    while true
      interactive_code = @engine.create_script_source_from_string(code, Scripting::SourceCodeKind.InteractiveCode)
      case interactive_code.get_code_properties
        when Scripting::ScriptCodeParseResult.Complete, Scripting::ScriptCodeParseResult.Invalid:
          return interactive_code
                    
        else
          print "#@language| "
          next_line = gets
          return interactive_code if next_line.nil? or next_line.strip.size == 0 
          code += next_line
      end      
    end
  end

  # Executes given ScriptSource and prints any exceptions that it might raise.
  def execute_code source
    source.execute(@scope)
  rescue Exception =&gt; e
    message, name = @exception_service.get_exception_message(e)
    puts "#{name}: #{message}"
  end

  def execute_command command
    case command
      when 'exit': exit
      when 'ls?': display_languages
      else puts "Unknown command '#{command}'" unless switch_language command
    end
  end

  def display_languages
    @engine.runtime.setup.language_setups.each { |ls| puts "#{ls.display_name}: #{ls.names.inspect}" }
  end

  def switch_language name
    has_engine, engine = @engine.runtime.try_get_engine(name)
    @language, @engine = name, engine if has_engine
    has_engine
  end
end

REPL.new.run
</pre>
<p>As you can see, we&#8217;ve encapsulated the code from previous posts into a class called &#8220;REPL&#8221;. We&#8217;ve added a support for meta commands, i. e. commands processed by the REPL itself. Any string starting with &#8220;#&#8221; chracter is treated as a meta command. The commands recognized are &#8220;#exit&#8221; and &#8220;#ls?&#8221;. The former terminates the REPL and the latter displays the available languages. If the command you enter is not one of these two we try to get an engine of that name and change the current language of the REPL. For example, &#8220;#py&#8221; makes Python the current language, which is indicated by the prompt &#8220;py&gt;&#8221;.</p>
<h3>More of DLR Hosting API</h3>
<p>We&#8217;ve used a couple of Hosting API concepts that we&#8217;ve not explained yet. They are, in order of appearance:</p>
<ul>
<li>Engine Services
<p>ScriptEngine represents a language in Hosting API. We already used it for code execution (ScriptEngine.Execute) and performing dynamic object operations (ScriptEngine.Operations). Apart from these basic functionality an engine can also provide various services that might or might not be language specific. The idea here is that if languages and hosts agree on a new dynamic language service API the languages can implement it and the hosts can consume it without modifications to DLR hosting API. It&#8217;s up to each language whether it provides a particular service, so the host should be prepared for the case that some of the languages it hosts might not respond to a service request.</p>
<p>Services are identified by the CLR type that provides the service API. The service we use in our REPL is ExceptionOperations from Microsoft.Scripting.Hosting namespace. It provides API for handling exceptions, formatting stack traces in a language specific way, etc. We use it in <i>execute_code</i> method to retrieve message and name from an exception raised by the executed script. A default exception operations are provided by DLR if the language doesn&#8217;t provide implementation.</p>
<li>Script Source
<p>So far we&#8217;ve used <i>ScriptEngine.Execute</i> for execution of code stored in a string. <i>ScriptEngine</i> also provides a set of methods prefixed <i>CreateScriptFrom-</i> that create <i>ScriptSource</i> objects representing source code stored in a string, file, stream, an editor buffer, etc. <i>ScriptSource</i> is mainly designed for hosts that need to provide a custom storage for the code, handle encoded code, analyze code, or pre-compile the code so that multiple executions are faster.</p>
<p>Each <i>ScriptSource</i> instance is also tagged by a value of <i>SourceCodeKind</i> enumeration. This value tells the language parser how to parse the code: whether it should be parsed as an expression, a single statement, multiple statements, like it was a file, or an interactive code snippet. The default value is <i>AutoDetect</i> meaning that the parser should parse any piece of code and decide from its structure what kind of code it is.</p>
<p>Internally, <i>ScriptEngine.Execute</i> creates a string based <i>ScriptSource</i> with code kind auto-detection and executes it.</p>
<p>In our REPL, <i>read_code</i> method creates an interactive <i>ScriptSource</i> from a string that user entered. It then queries the <i>ScriptSource</i> for its code properties. <i>ScriptSource</i> asks the parser of the language is it bound to to parse the code and determine whether it is correct and complete, incorrect (has a syntax error), correct but its last token is incomplete (for example, an unterminated string literal), correct but the last statement is incomplete (for example, &#8220;1+&#8221;). These properties are captured by <i>ScriptCodeParseResult</i> enumeration in <i>Microsoft.Scripting</i> namespace. We use this value in <i>read_code</i> to determine if we should continue reading lines from the input. We continue reading until we get a complete or invalid code.</p>
</li>
</ul>
<h3>.NET interop</h3>
<p>We have just explained what Hosting APIs we use in the REPL, yet there is still some magic going on in how we call these APIs from Ruby. Let&#8217;s look at .NET interop involved here. </p>
<ul>
<li>Generic method call
<p>The first piece of .NET interop magic is used in <i>REPL#initialize</i> method. We have an instance of <i>ScriptEngine</i> in <i>@engine</i> variable and we want to get its <i>ExceptionOperations</i> service. <i>ScriptEngine.GetService&lt;TService&gt;</i> is a generic method. To invoke a generic method you need to provide the generic parameters somehow. The way it works in IronRuby right now is not ideal but one gets the job done nevertheless. Calling <i>Kernel#method</i> on an object gives us a Ruby <i>Method</i> object that represents the (generic) method. IronRuby monkey-patches this class adding <i>Method#of</i> method that takes a list of classes/modules that represent .NET types and returns a new instance of <i>Method</i> class with the method&#8217;s generic parameters bound to the given types. Once the generic parameters are bound the method is callable like any other Ruby method (i.e. via <i>Method#call</i>).</p>
<li>Out parameters
<p>The call to <i>try_get_engine</i> in <i>switch_language</i> doesn&#8217;t seem to be any special at the first glance. However, if you look at the C# implementation of <i>ScriptRuntime.TryGetEngine</i> method, you&#8217;ll see that it has two parameters, second of which is an out-parameter:</p>
<pre>bool TryGetEngine(string languageName, out ScriptEngine engine)
</pre>
<p>When IronRuby encounters a call to such a method it basically takes all the out parameters in the order they appear in the signature and returns them in a CLR array along with the return value. Like if the method&#8217;s implementation was as follows:</p>
<pre>object[] TryGetEngine(string languageName) {
  ...
  return new object[] { return_value, engine }
}
</pre>
<p>IronRuby is able to splat CLR vector arrays. In fact, any class implementing <i>IList</i> interface can be splatted. Hence the parallel assignment we use in <i>switch_language</i> assigns the return value (a Boolean) to <i>has_engine</i> and the value of the out parameter to <i>engine</i> local variable.</p>
</li>
</ul>
<h3>Python interop preview</h3>
<p>Finally, we can enter Ruby multi-line snippets and also some Python code!</p>
<pre>rb&gt; class C
rb|   def say_hello caller
rb|     puts "#{caller} says hello to Ruby"
rb|   end
rb| end
=&gt; nil
rb&gt; #py
py&gt; import C
py&gt; c = C()
py&gt; c.say_hello("Python")
Python says hello to Ruby</pre>
<p>This is a nice little example of Ruby-Python interop that gives you a taste of DLR potential. What’s going on here? First we declared a class C in Ruby with a method <em>say_hello</em>. Then we switched over to Python (using &#8220;#py&#8221; meta command) and executed some Python code. We imported &#8220;C&#8221; global variable to the local Python scope. IronRuby maps all constants defined on <em>Object</em> class to DLR global variables. IronPython maps its global variables to the DLR globals as well. Hence IronRuby and IronPython see each other’s variables and can exchange them. </p>
<p>Now that we successfully imported Ruby class object &#8220;C&#8221; into Python we can call it, right? Wait a second! You can’t call a Ruby class! Well, that’s right, but we are in Python – a call to a class object in Python makes an instance of the class. Python has no <em>new </em>method like Ruby has or <em>new</em> keyword like C# has. When IronPython sees an invocation of a dynamic object that is not its own it sends it an DLR interop message “Invoke”. IronRuby’s class objects don’t respond to this message. After all you can’t call a Ruby class. IronPython is smart and knows that if the object doesn’t respond to “Invoke” message it might respond to “CreateInstance” message. And so it sends the “CreateInstance” message to which the Ruby class responds by sending over a new instance of itself. And after a short chat between IronPython and IronRuby mediated by DLR, we store an instance of class <em>C</em> in Python’s local variable <em>c</em>. </p>
<p>We call <em>say_hello</em> method on the next line. Since we are in Python there are actually two operations involved here: “GetMember” and “Invoke”. Python first asks the object for its member <em>say_hello </em>(by sending “GetMember” message to the object). The Ruby object knows how to get a member – it returns an instance of <em>Method</em> class that represents <em>say_hello</em> method. Python now asks to invoke the returned object and indeed Ruby&#8217;s <em>Method</em> knows how to invoke itself.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</p>
<pre></pre>
<pre></pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matousek.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/matousek.wordpress.com/50/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=50&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://matousek.wordpress.com/2009/04/15/python-says-hello-to-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb51033949ffccd982ae32c9f890f25a?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">tomasmatousek</media:title>
		</media:content>
	</item>
		<item>
		<title>Multilingual REPL</title>
		<link>http://matousek.wordpress.com/2009/02/20/multilingual-repl/</link>
		<comments>http://matousek.wordpress.com/2009/02/20/multilingual-repl/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 07:10:00 +0000</pubDate>
		<dc:creator>tomasmatousek</dc:creator>
				<category><![CDATA[IronRuby]]></category>
		<category><![CDATA[DLR]]></category>
		<category><![CDATA[IronPython]]></category>
		<category><![CDATA[REPL]]></category>

		<guid isPermaLink="false">http://matousek.wordpress.com/?p=39</guid>
		<description><![CDATA[DLR Hosting API is a common API for all DLR languages: IronRuby, IronPython, and others. It abstracts away language specific details and provides API that could be used in a language independent manner. The API is primarily designed to ease usage of dynamic languages from strongly typed .NET languages and to make it easier to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=39&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>DLR Hosting API is a common API for all DLR languages: <a href="http://ironruby.net" target="_blank">IronRuby</a>, <a href="http://codeplex.com/IronPython" target="_blank">IronPython</a>, and others. It abstracts away language specific details and provides API that could be used in a language independent manner. The API is primarily designed to ease usage of dynamic languages from strongly typed .NET languages and to make it easier to write applications with a scriptable object model. Nonetheless we can take advantage of the API in a scripting language as well. For that purpose the most interesting features are management of isolated scripting environments (<em>script runtimes</em>) and cross language code execution. I presented the former in my <a href="http://matousek.wordpress.com/2008/12/27/isolated-code-execution/" target="_blank">last post</a>. Let’s check out the latter today.</p>
<p>To run examples below you’ll need to build the latest IronRuby, IronPython and DLR from sources. You can do so using the latest sources from <a href="http://github.com/ironruby/ironruby/tree/master" target="_blank">IronRuby GIT repository</a> or <a href="http://www.codeplex.com/dlr/SourceControl/ListDownloadableCommits.aspx" target="_blank">DLR CodePlex site</a>:</p>
<ul>
<li>Building from IronRuby GIT repo (mapped locally to C:\Git\ironruby):
<p>C:\Git\ironruby\Merlin\Main &gt; msbuild Languages\Ruby\Ruby.sln        <br />C:\Git\ironruby\Merlin\Main &gt; msbuild Languages\IronPython\IronPython.sln </p>
<p>We’ve recently included IronPython projects to the repository. If you already have the repo set up just pull the latest commit. You can also use rake to build IronRuby, we don&#8217;t provide rake file for IronPython though.</p>
</li>
<li>Building from DLR CodePlex (downloaded and extracted to C:\CodePlex\DLR_Main):
<p>C:\Codeplex\DLR_Main &gt; msbuild Codeplex-DLR.sln</p>
</li>
</ul>
<p>Both builds build unsigned debug assemblies and place the binaries into bin\Debug directory.</p>
<h3>Available Languages</h3>
<p>The DLR runtime can host multiple languages at once. Listing all languages that are available is easy:</p>
<pre><span style="color:green;"># github: <a href="http://github.com/tmat/blog/tree/master/multilingual-repl/languages.rb" target="_blank">languages.rb</a></span>
# load IronRuby library that provides Ruby programs an easy access to the Hosting API:
require 'IronRuby'

# create a new DLR runtime:
runtime = IronRuby.create_runtime
  
# list all available languages:
runtime.setup.language_setups.each { |ls| puts &quot;#{ls.display_name}: #{ls.names.inspect}&quot; }</pre>
<p>The last line enumerates all instances of <em>LanguageSetup</em> class (defined by Hosting API) that are stored in the setup of the runtime. For each such language setup its display name and a list of short names are printed. The short names uniquely identify languages within the runtime. A language can be identified by multiple short names.</p>
<pre>C:\Codeplex\DLR_Main\Bin\Debug&gt;ir languages.rb
IronPython 2.6 Alpha: [&quot;IronPython&quot;, &quot;Python&quot;, &quot;py&quot;]
IronRuby 1.0 Alpha: [&quot;IronRuby&quot;, &quot;Ruby&quot;, &quot;rb&quot;]
ToyScript: [&quot;ToyScript&quot;, &quot;ts&quot;]</pre>
<p>Where does this list come from? We have said nothing about IronPython in our script. Does IronRuby know about IronPython? Making IronRuby dependent on all languages it could possibly interact with wouldn’t be a good design. Instead, Hosting API creates and sets up a script runtime according to the current .NET application’s configuration. It is told to do so in <em>IronRuby#create_runtime</em>. The .NET application is <em>ir.exe</em> hence the configuration is loaded from <em>ir.exe.config</em> file that lives next to the <em>ir.exe</em>. Indeed, the list of languages can be found in this file:</p>
<pre>&lt;languages&gt;
  &lt;language names=&quot;IronPython;Python;py&quot; extensions=&quot;.py&quot; displayName=&quot;IronPython 2.6 Alpha&quot;
    type=&quot;IronPython.Runtime.PythonContext, IronPython, Version=2.6.0.1, Culture=neutral, PublicKeyToken=null&quot; /&gt;
  &lt;language names=&quot;IronRuby;Ruby;rb&quot; extensions=&quot;.rb&quot; displayName=&quot;IronRuby 1.0 Alpha&quot;     
    type=&quot;IronRuby.Runtime.RubyContext, IronRuby, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot; /&gt;
  &lt;language names=&quot;ToyScript;ts&quot; extensions=&quot;.ts&quot;    
    type=&quot;ToyScript.ToyLanguageContext, ToyScript, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot; /&gt;
&lt;/languages&gt;</pre>
<p>Whenever you find a DLR language you want to use for scripting your app and don&#8217;t have yet you can just add it to the list and you’re all set.</p>
<h3>Hosting IronPython in IronRuby</h3>
<p>Now that we know how IronPython identifies itself to the runtime, we can load its engine and execute some Python code. Let&#8217;s take the simple REPL implementation from the previous post and change it to execute Python code instead of Ruby:</p>
<pre><span style="color:green;"># github: <a href="http://github.com/tmat/blog/tree/master/multilingual-repl/python_repl.rb" target="_blank">python_repl.rb</a></span>
require 'IronRuby'
runtime = IronRuby.create_runtime

# ask the runtime for Python engine using one of its simple names:
engine = runtime.get_engine(&quot;IronPython&quot;)

scope = engine.create_scope

while true  
  print &quot;&gt; &quot;
  code = gets
  break if code.nil?
  begin
    result = engine.execute(code, scope)

    # print the Ruby's view of the result:
    p result

    # print the result as Python would display it:
    puts engine.operations.format(result)
  rescue Exception
    puts $!
  end
end</pre>
<p>Let&#8217;s play now:</p>
<pre>C:\Codeplex\DLR_Main\Bin\Debug&gt;ir python_repl.rb
&gt; def add(a,b): return a + b
nil
None
&gt; add
#&lt;IronPython::Runtime::PythonFunction:0x000005c&gt;
&lt;function add at 0x000000000000002B&gt;
&gt; add(1,1)
2
2
&gt; add((1, 2), (3, 4))
#&lt;IronPython::Runtime::PythonTuple:0x000005e&gt;
(1, 2, 3, 4)
&gt; ^Z</pre>
<p>As you can see, each language might have a different view on the same object.</p>
<p>To make the REPL really useful we need to support multi-line statements (i.e. wait with code execution until a complete statement is entered). Let&#8217;s keep that and more for the next post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matousek.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/matousek.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=39&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://matousek.wordpress.com/2009/02/20/multilingual-repl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb51033949ffccd982ae32c9f890f25a?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">tomasmatousek</media:title>
		</media:content>
	</item>
		<item>
		<title>Isolated Code Execution</title>
		<link>http://matousek.wordpress.com/2008/12/27/isolated-code-execution/</link>
		<comments>http://matousek.wordpress.com/2008/12/27/isolated-code-execution/#comments</comments>
		<pubDate>Sat, 27 Dec 2008 14:05:24 +0000</pubDate>
		<dc:creator>tomasmatousek</dc:creator>
				<category><![CDATA[IronRuby]]></category>
		<category><![CDATA[DLR]]></category>
		<category><![CDATA[irb]]></category>
		<category><![CDATA[isolated code execution]]></category>
		<category><![CDATA[REPL]]></category>

		<guid isPermaLink="false">http://matousek.wordpress.com/2008/12/27/isolated-code-execution/</guid>
		<description><![CDATA[Every Ruby programmer is familiar with irb &#8211; an interactive Ruby shell, aka REPL (Read-Eval-Print Loop). It is a handy tool for discovering how Ruby language features or libraries work. It has some limitations though. It is entirely written in Ruby and so you might bump into a problem like this: C:\Program Files\Ruby\bin&#62; irb irb(main):001:0&#62; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=23&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Every Ruby programmer is familiar with <em><a href="http://en.wikipedia.org/wiki/Interactive_Ruby_Shell" target="_blank">irb</a> &#8211; </em>an interactive Ruby shell, aka REPL (<a href="http://en.wikipedia.org/wiki/REPL" target="_blank">Read-Eval-Print Loop</a>). It is a handy tool for discovering how Ruby language features or libraries work. It has some limitations though. It is entirely written in Ruby and so you might bump into a problem like this:</p>
<pre>C:\Program Files\Ruby\bin&gt; irb
irb(main):001:0&gt; class Fixnum
irb(main):002:1&gt;   remove_method :+
irb(main):003:1* end
=&gt; Fixnum
irb(main):004:0&gt; 1
C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb/input-method.rb:99:in `gets': undefined method `+' for
3:Fixnum (NoMethodError)
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb.rb:132:in `eval_input'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb.rb:259:in `signal_status'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb.rb:131:in `eval_input'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb/ruby-lex.rb:189:in `call'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb/ruby-lex.rb:189:in `buf_input'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb/ruby-lex.rb:104:in `getc'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb/slex.rb:206:in `match_io'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb/slex.rb:76:in `match'
         ... 8 levels...
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb.rb:70:in `start'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb.rb:69:in `catch'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/lib/ruby/1.8/irb.rb:69:in `start'
        from C:/M1/Merlin/External/Languages/Ruby/ruby-1.8.6/bin/irb:13 
C:\Program Files\Ruby\bin&gt; </pre>
<p>Oops. What happened? We removed method &#8220;+&#8221; from Fixnum class and, accidentally, irb itself uses that method somewhere in the REPL implementation. The solution is obvious. Run any user code typed in an isolated environment (or &#8220;virtual machine&#8221;) different from the one that drives the REPL. Let&#8217;s take a look how to do this in IronRuby.</p>
<h3>Hosting API</h3>
<p>The <a href="http://www.codeplex.com/dlr" target="_blank">Dynamic Language Runtime</a> (DLR), which IronRuby is built on top of, provides API for hosting dynamic languages in an arbitrary .NET application (see Hosting API <a href="http://www.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=dlr&amp;DownloadId=51532" target="_blank">specification</a>). You only need to know a few concepts to use this API in a powerful way. The first is <em>script runtime</em>. Each instance of ScriptRuntime class provides an environment for script execution. The runtime hosts scripting language <em>engines</em>. A single runtime can host engines of multiple DLR languages (IronRuby, IronPython, etc.), at most one engine for each language. Each engine is represented by an instance of ScriptEngine class. It holds on a global state that the particular language defines. IronRuby engine, for example, maintains a dictionary of global variables, objects that represent Ruby modules and classes, the list of loaded Ruby files, etc. An application can create any number of ScriptRuntimes and thus any number of IronRuby or IronPython &#8220;virtual machines&#8221; in a single process. </p>
<p>Hosting API is implemented in C# in Microsoft.Scripting.dll assembly distributed with IronRuby. IronRuby has a rich support for .NET interop, so we could load this assembly and use the Hosting API classes directly from IronRuby scripts. Although it would be simple we made it even easier: IronRuby comes with <em>IronRuby</em> module that provides basic hosting API specialized for Ruby. </p>
<h3>Ruby REPL Based on Hosting API</h3>
<p>A very simple REPL in Ruby might read as follows.</p>
<pre># load IronRuby library
require 'IronRuby'

# create a new IronRuby engine and a new runtime:
engine = IronRuby.create_engine

while true  
  print "&gt; "
  code = gets
  break if code.nil?
  begin
    p engine.execute(code)
  rescue Exception
    puts $!
  end
end
</pre>
<p>The REPL script itself runs in a script runtime created by ir.exe host. The code typed in the loop is evaluated in the runtime created by <em>IronRuby#create_engine</em>. The result of <em>ScriptEngine#execute</em> is sent to the calling runtime and printed out via <em>Kernel#p</em> method. </p>
<pre>C:\IronRuby\Merlin\Main\Bin\Debug\ir.exe repl.rb
&gt; 1+1
2
&gt; Fixnum.send :remove_method, :+
Fixnum@2
&gt; 1+1
undefined method `+' for 1:Fixnum
&gt; 2.times { |i| puts i }
0
1
2
&gt; ^Z</pre>
<p>Note that there are as many class objects for each class as there are runtimes in which the class is used. IronRuby appends &#8220;@n&#8221; to the name of a class that comes from a different runtime, whose id is <em>n, </em>to differentiate it from the class of the same name in the current runtime. Hence <em>Module#remove_method</em>, which returns the class the method has been removed from, returns &#8220;Fixnum@2&#8243;.</p>
<p>There are many ways in which we can make our REPL better. The most serious deficiency can be easily demonstrated:</p>
<pre>&gt; x = 1
1
&gt; puts x
undefined method `x' for main:Object</pre>
<p>Why we got an exception? We defined a local variable <i>x</i> in the first line, so why is it not available in the second line? We are missing some kind of variable dictionary shared among multiple snippet executions. If we used <em>Kernel#eval</em> in Ruby we would pass an instance of <em>Binding</em> to it. The Hosting API uses a similar concept: <em>script scope</em>. I&#8217;m going to explain DLR scopes in a separate blog post in detail. Let&#8217;s just say for now that IronRuby associates a top-level Ruby binding with each ScriptScope class instance against which it executes code. We need to make a very simple change in our REPL script to use DLR scopes:</p>
<pre><span style="color:green;"># github: <a href="http://github.com/tmat/blog/tree/master/isolated-code-execution/repl.rb" target="_blank">repl.rb</a></span>
require 'IronRuby'
engine = IronRuby.create_engine
<span style="background-color:yellow;">scope = engine.create_scope</span>

while true  
  print "&gt; "
  code = gets
  break if code.nil?
  begin
    p engine.execute(code, <span style="background-color:yellow;">scope</span>) 
  rescue Exception
    puts $!
  end
end
</pre>
<p>Local variables work as expected now (actually, the fix in IronRuby source code that makes this work is not yet committed to the public repo, it&#8217;s coming soon though):</p>
<pre>&gt; x = 1
1
&gt; puts x
1
nil</pre>
<p>Another feature our simple REPL lacks is handling of multi-line expressions and statements. Let&#8217;s keep that and more for the next blog post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matousek.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/matousek.wordpress.com/23/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=23&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://matousek.wordpress.com/2008/12/27/isolated-code-execution/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb51033949ffccd982ae32c9f890f25a?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">tomasmatousek</media:title>
		</media:content>
	</item>
		<item>
		<title>Ruby flip-flop operator</title>
		<link>http://matousek.wordpress.com/2008/12/06/ruby-flip-flop-operator/</link>
		<comments>http://matousek.wordpress.com/2008/12/06/ruby-flip-flop-operator/#comments</comments>
		<pubDate>Sun, 07 Dec 2008 02:12:29 +0000</pubDate>
		<dc:creator>tomasmatousek</dc:creator>
				<category><![CDATA[Ruby features]]></category>

		<guid isPermaLink="false">http://matousek.wordpress.com/2008/12/06/ruby-flip-flop-operator/</guid>
		<description><![CDATA[Although its usage is discouraged the flip-flop operator – a range used in a condition – is still a Ruby language feature. Let&#8217;s take a look at how IronRuby implements it. First, we need to figure out what exactly it is supposed to do. The general behavior is described in books on Ruby, however to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=12&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Although its usage is discouraged the <i><a target="_blank" href="http://www.rubycentral.com/pickaxe/tut_expressions.html#S6">flip-flop operator</a></i> – a range used in a condition – is still a Ruby language feature. Let&#8217;s take a look at how IronRuby implements it. First, we need to figure out what exactly it is supposed to do. The general behavior is described in books on Ruby, however to implement it in a compiler you need to sort out all the edge cases. So let&#8217;s play with it a little.</p>
<h5>What distinguishes a flip-flop from a range?</h5>
<p>The syntax is the same: <i>expression</i> ‘..’ <i>expression</i> (end-inclusive range) or <i>expression</i> ‘&#8230;’ <i>expression</i> (end-exclusive range). A range is considered a flip-flop operator if any of its bound is not an integer literal and if it is used as a <i>condition</i> of the following expressions:</p>
<ul>
<li><i>condition</i> ‘?’ <i>expression</i> ‘:’ <i>expression</i> </li>
<li><i>statement</i> ‘if’ <i>condition</i> </li>
<li><i>statement</i> ‘unless’ <i>condition</i> </li>
<li><i>statement</i> ‘while’ <i>condition</i> </li>
<li><i>statement</i> ‘until’ <i>condition</i> </li>
<li>‘if’ <i>condition</i> <i>then</i> <i>statements</i> <i>if-tail</i> ‘end’ </li>
<li>‘unless’ <i>condition</i> <i>then</i> <i>statements</i> <i>else-opt</i> ‘end’ </li>
<li>‘while’ <i>condition </i>‘do’ <i>statements</i> ‘end’ </li>
<li>‘until’ <i>condition </i>‘do’ <i>statements</i> ‘end’ </li>
</ul>
<p>For example:</p>
<pre>irb(main):001:0&gt; 1 if TRUE..FALSE 
=&gt; 1</pre>
<p>In addition, parenthesized ranges used in a condition are also flip-flops, e.g.: </p>
<pre>irb(main):001:0&gt; 1 if (TRUE..FALSE) 
=&gt; 1</pre>
<p>‘(‘ <i>statements</i> ‘)’ is a <i>block expression</i> with a single statement expression TRUE..FALSE. If there are more statements in the block in front of the range it is no longer a flip-flop operator:</p>
<pre>irb(main):008:0&gt; 1 if (puts;TRUE..FALSE) 
ArgumentError: bad value for range </pre>
<p>The exception is raised since a range bounds cannot be Booleans.</p>
<p>Any number of nested <i>block expressions</i> works:</p>
<pre>irb(main):001:0&gt; 1 if ((((TRUE..FALSE)))) 
=&gt; 1 </pre>
<p>And <i>begin</i>-<i>end</i> blocks work as well: </p>
<pre>irb(main):032:0&gt; 1 if begin TRUE..FALSE end 
=&gt; 1 </pre>
<p>As do any combinations of the two (but only in Ruby 1.9, in Ruby 1.8.6 some combinations don’t work, which I consider a bug):</p>
<pre>irb(main):001:0&gt; 1 if (begin (((begin begin TRUE..FALSE end end))) end) 
=&gt; 1 </pre>
<p>Also, ranges used in Boolean expressions used as conditions are considered flip-flops: </p>
<pre>irb(main):018:0&gt; 1 if t(1)..f(2) and not t(3)..f(4) or t(5)..f(6) 
123456=&gt; 1 
irb(main):018:0&gt; 1 if (t(1)..f(2)) &amp;&amp; !(t(3)..f(4)) || (t(5)..f(6)) 
123456=&gt; 1 </pre>
<p>where <i>t</i> and <i>f</i> are functions that print the argument and return <i>true</i> and <i>false</i> respectively. The second example also doesn’t work in Ruby 1.8.6, oups. </p>
<p>Let’s summarize what have we just found out: block expressions (parenthesized or <i>begin-end</i>) containing a single range and Boolean expressions propagate the “in-condition” property to their children AST nodes. The “in-condition” property then turns ranges into flip-flop operators. Other nodes don’t propagate it. A <em>method call </em>doesn’t, for example: </p>
<pre>irb(main):018:0&gt; 1 if puts(t(1)..f(2)) 
ArgumentError: bad value for range </pre>
<p>Side note: this property is also applied on regular expressions. If a regex is “in-condition” it is compiled as a match against $_ variable: </p>
<pre>irb(main):029:0&gt; $_ = 'xz' 
=&gt; &quot;xz&quot; 
irb(main):030:0&gt; 1 if /y/ or ((begin((/x/ and /(z)/))end)) 
=&gt; 1 
irb(main):031:0&gt; $1 
=&gt; &quot;z&quot; </pre>
<h5>How does flip-flop work?</h5>
<p>We know from the books that flip-flop would probably define some state variable that changes values as the expressions of the operator are evaluated. To figure out how exactly it works I wrote a simple script:</p>
<pre>F = false
T = true
x = X = '!'

B = [F,T,x,x,x,T,x,F,F]
E = [x,x,F,F,T,x,T,x,x]
       
def b
  step('b',B)
end

def e
  step('e',E)
end

def step name,value
  r = value[$j]
  puts &quot;#{$j}: #{name} -&gt; #{r.inspect}&quot;
  
  $j += 1
  
  $continue = !r.nil?  
  r == X ? raise : r  
end

$j = 0
$continue = true
while $continue
  if b..e 
    puts &quot;#{$j}: TRUE&quot; 
  else
    puts &quot;#{$j}: FALSE&quot; 
  end
end</pre>
<p>In this code we evaluate an end-inclusive flip-flop in a loop. Each time the flip-flop operator is evaluated ‘b’ or ‘e’ method is called, or both methods are called. Global variable $j is an index into B and E arrays defined at the top. The arrays define a sequence of values the methods <i>b</i> and <i>e</i> should return. If <i>x</i> value (‘!’) is to be returned an exception is thrown. This way we can track what the automaton behind the flip-flop operator does. Using the output of the script we can easily deduce how the automaton could look like:</p>
<pre>0: b -&gt; false
1: FALSE
1: b -&gt; true
2: TRUE
2: e -&gt; false
3: TRUE
3: e -&gt; false
4: TRUE
4: e -&gt; true
5: TRUE
5: b -&gt; true
6: TRUE
6: e -&gt; true
7: TRUE
7: b -&gt; false
8: FALSE
8: b -&gt; false
9: FALSE
9: b -&gt; nil
10: FALSE.</pre>
<p><a href="http://matousek.files.wordpress.com/2008/12/flipflop.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="Flip-Flop" border="0" alt="Flip-Flop" src="http://matousek.files.wordpress.com/2008/12/flipflop-thumb.png?w=304&#038;h=258" width="304" height="258" /></a> </p>
<p>It has four states: BEFORE, INSIDE, AFTER and a lambda state. In each state <i>b</i> or <i>e</i> expression is evaluated and the automaton transitions to another state based upon the result: <i>true</i> (T) or <i>false</i> (F). If it transitions to INSIDE or AFTER state the flip-flop operator returns <i>true</i>. If it transitions to BEFORE state the operator returns <i>false</i>. If it transitions to the lambda state the operator evaluates <i>b</i> and does one more transition. </p>
<p>The previous automaton works for an end-inclusive flip-flop operator. The one bellow does for an end-exclusive operator – the lambda state is gone: </p>
<p><a href="http://matousek.files.wordpress.com/2008/12/flipflopexclusive.png"><img style="display:inline;" title="Flip-Flop-Exclusive" border="0" alt="Flip-Flop-Exclusive" src="http://matousek.files.wordpress.com/2008/12/flipflopexclusive-thumb.png?w=304&#038;h=258" width="304" height="258" /></a> </p>
<h5>What code does IronRuby emit?</h5>
<p>We emit the following code for end-inclusive flip-flop operator {begin}..{end}: </p>
<pre>if state || IsTrue({begin})
  state = IsFalse({end})
  true
else  
  false
end  </pre>
<p>The state variable is a Boolean and it’s <em>true </em>iff the automaton is in INSIDE or lambda state. In both states this means evaluate {end}<em> </em>expression, transition to the state given by negated result and return <em>true</em>. If the state variable is <em>false</em> we are either in AFTER or in BEFORE state. In any case {begin} is evaluated. If it returns <em>false</em> we go to/stay in BEFORE state and the result of the flip-flop operator is <em>false</em>. Otherwise we go to the lambda state and evaluate <em>end</em>.</p>
<p>Similarly, the end-exclusive flip-flop operator {begin}&#8230;{end} is implemented as</p>
<pre>if state
  state = IsFalse({end}) 
  true
else
  state = IsTrue({begin})
end</pre>
<p>&#160;</p>
<p>The state variable is allocated in the inner-most method scope. A flip-flop operator used in a block preserves the state across multiple calls to the block:</p>
<pre>def y *a; yield *a; end

def test
  $p = proc { |b,e|
    puts b..e ? TRUE : FALSE
  }
  
  y false, &amp;$p  
  y true, true, &amp;$p
  y false, &amp;$p
  y true, false, &amp;$p
end

test</pre>
<p>Output:</p>
<pre>false 
true 
false 
true </pre>
<p>The method that transforms IronRuby’s RangeExpression node into DLR AST in the case the range is a flip-flop operator looks like:</p>
<pre class="csharpcode"><span class="kwrd">private</span> MSA.Expression<span class="rem">/*!*/</span> TransformReadCondition(AstGenerator<span class="rem">/*!*/</span> gen) {
    <span class="rem">// Define state variable in the inner most method scope.</span>
    <span class="kwrd">var</span> stateVariable = gen.CurrentMethod.Builder.DefineHiddenVariable(<span class="str">&quot;#in_range&quot;</span>, <span class="kwrd">typeof</span>(<span class="kwrd">bool</span>));

    <span class="kwrd">var</span> begin = Ast.Box(_begin.TransformRead(gen));
    <span class="kwrd">var</span> end = Ast.Box(_end.TransformRead(gen));

    <span class="kwrd">if</span> (_isExclusive) {
        <span class="kwrd">return</span> Ast.Condition(
            stateVariable,
            Ast.Comma(Ast.Assign(stateVariable, Methods.IsFalse.OpCall(end)), Ast.True()),
            Ast.Assign(stateVariable, Methods.IsTrue.OpCall(begin))
        );  
    } <span class="kwrd">else</span> {
        <span class="kwrd">return</span> Ast.Condition(
            Ast.OrElse(stateVariable, Methods.IsTrue.OpCall(begin)),
            Ast.Comma(Ast.Assign(stateVariable, Methods.IsFalse.OpCall(end)), Ast.True()),
            Ast.False()
        );
                          
    }
}</pre>
<p>This code can be found in <i>Ruby\Compiler\Ast\Expressions\RangeExpression.cs.</i> Propagation of “in-condition” property to AST nodes is performed by <i>ToCondition</i> virtual method overridden by RangeExpression, RegularExpression, AndExpression, OrExpression and BodyExpression and called from parser (<i>Ruby\Compiler\Parser\Parser.y</i>). </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/matousek.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/matousek.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=matousek.wordpress.com&#038;blog=5595917&#038;post=12&#038;subd=matousek&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://matousek.wordpress.com/2008/12/06/ruby-flip-flop-operator/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cb51033949ffccd982ae32c9f890f25a?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">tomasmatousek</media:title>
		</media:content>

		<media:content url="http://matousek.files.wordpress.com/2008/12/flipflop-thumb.png" medium="image">
			<media:title type="html">Flip-Flop</media:title>
		</media:content>

		<media:content url="http://matousek.files.wordpress.com/2008/12/flipflopexclusive-thumb.png" medium="image">
			<media:title type="html">Flip-Flop-Exclusive</media:title>
		</media:content>
	</item>
	</channel>
</rss>
