<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
		<title>Topten Software</title>
		<link>http://www.toptensoftware.com</link>
		<copyright>copyright &#169; 2011 Topten Software</copyright>
		<description></description>
		<managingEditor>Brad Robinson</managingEditor>
		<language>en-US</language>
		<generator>Jab2</generator>
		<atom:link href="www.toptensoftware.com/Feed" rel="self" type="application/rss+xml" />
<item>
			<title>Change of Plans, Prefix Shelved.</title>
			<author>brobinson</author>
			<pubDate>Sun, 20 Nov 2011 00:00:00 GMT</pubDate>
			<description><![CDATA[<p>I've decided to suspend development of Prefix for the time being.</p>
<p>As you may have noticed I haven't posted anything here for a while - primarily because development of Prefix has been suspended.  There's a couple of reasons for this, but the main two are:</p>
<ol>
<li>We've decided to cease operations at the company where I work my day job.  Commencing 2012 I'll be officially out of work and looking for something new to do.</li>
<li>Given that I can't figure out how to commercialize Prefix, it needs to be put on the back-burner to make room for something that will pay the bills.</li>
</ol>
<p>I'd like to return to Prefix at some stage but for the moment at least it's shelved.  Besides Prefix I also have several other unpublished projects which have also been suspended - the slate needs to be cleared.</p>
<p>Having said all that, this seems to be the perfect opportunity to look for something completely different to work on.  So over the coming month(s) I think I'll try my hand at various random things to see what piques my interest.  Perhaps something in the mobile space, maybe some game development, perhaps something else.  Who knows?</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/136/Change-of-Plans-Prefix-Shelved</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/136/Change-of-Plans-Prefix-Shelved</guid>
			<comments>http://www.toptensoftware.com/Articles/136/Change-of-Plans-Prefix-Shelved</comments>
			<category>Miscellaneous</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - ForEach Statements</title>
			<author>brobinson</author>
			<pubDate>Thu, 29 Sep 2011 23:54:33 GMT</pubDate>
			<description><![CDATA[<p>Prefix now supports <code>foreach</code> loops but their not exactly as you might expect....</p>
<p><em>This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>Prefix has had <code>for</code> loops pretty much since day one.  I'd deliberately left out <code>foreach</code> loops until now because I wanted to integrate them with some sort of enumerable/generator (eg: <code>IEnumerable&lt;T&gt;</code>) mechanism, but I've decided to put that off for now and just aim for parity with JavaScript functionality.</p>
<h2 id="enumerating-array-like-objects">Enumerating Array Like Objects</h2>
<p>First up, the Prefix <code>foreach</code> statement will work with any type that implements a <code>int length</code> variable or property and an indexer that takes an integer parameter - including obviously arrays and strings.</p>
<p>Prefix uses a temporary variable as the counter and just enumerates the collection as you'd expect:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

var x = new string[];
x.push(&quot;Hello&quot;);
x.push(&quot;World&quot;);

foreach (var i in x)
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
var $temp;
var x=[];
x.push(&quot;Hello&quot;);
x.push(&quot;World&quot;);
for ($temp=0; $temp&lt;x.length; $temp++)
{
    var i = x[$temp];
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<p>The generated code will use an additional temporary variable if the expression begin enumerated might cause side effects.  In this example, <code>$temp2</code> is used to hold the array to avoid multiple calls into <code>fn</code>:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

string[] fn()
{
    var x = new string[];
    x.push(&quot;Hello&quot;);
    x.push(&quot;World&quot;);
    return x;
}

foreach (var i in fn())
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function fn()
{
    var x=[];
    x.push(&quot;Hello&quot;);
    x.push(&quot;World&quot;);
    return x;
};

// Start Global Code
var $temp, $temp2;
for ($temp=0, $temp2=fn(); $temp&lt;$temp2.length; $temp++)
{
    var i = $temp2[$temp];
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<p>(in case you're wondering, Prefix tracks temporary variable allocations and re-uses them, so multiple consecutive loops like this will declare the temporary variables once at the top of the scope (function) and re-use them multiple times over).</p>
<h2 id="enumerating-dictionaries">Enumerating Dictionaries</h2>
<p>I've always thought object enumeration in JavaScript to be a little messy - though I do understand the reasons for it.  In JavaScript there's two main reasons for enumerating an object - to get all the values of a associative array, or to enumerate all the methods, properties, fields of an object (say to dump/inspect it).  The differences with these two approaches relates to whether to enumerate the prototype chain or not.  
</p>
<p>The JavaScript <code>for...in</code> statement does enumerate the prototype chain. If you only want the immediate properties of the object (say the keys of a dictionary) you need to use the <code>hasOwnProperty</code> method to detect the items to exclude.</p>
<p>In Prefix, the call to <code>hasOwnProperty</code> <em>is included automatically</em> in generated <code>foreach</code> loops.  
</p>
<p>(In the following example I'm using backtick escapes to declare literal JavaScript - to better show the object layout).</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

// Purposely put something that doesn't belong in the object prototype
// This SHOULD NOT appear in the output
`Object.prototype.somecrap = 23`;

// Create a dictionary
var dict = `{apple:1, pear:2, banana:3}`;

// Dump the contents of the dictionary
foreach (var i in dict)
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
Object.prototype.somecrap = 23;
var dict={apple:1, pear:2, banana:3};
for (var i in dict)
{
    if (!dict.hasOwnProperty(i))
        continue;
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<h2 id="enumerating-object-members">Enumerating Object Members</h2>
<p>The above example raises the obvious question of how to enumerate the entire prototype chain? Well, with a new form of the foreach statement:   <code>foreach member (var i in whatever)</code>.</p>
<p>The following example is the same as the above but I've added the <code>member</code> pseudo-keyword:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

// Purposely put something that doesn't belong in the object prototype
// This SHOULD appear in the output
`Object.prototype.somecrap = 23`;

// Create a dictionary
var dict = `{apple:1, pear:2, banana:3}`;

// Dump all members of the dictionary (including the extra property in the object prototype)
foreach member (var i in dict)
{
    Console.WriteLine(i);
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
Object.prototype.somecrap = 23;
var dict={apple:1, pear:2, banana:3};
for (var i in dict)
{
    Console.WriteLine(i);
}

})();
</code></pre>
</div>
<p>The <code>member</code> modifier can also be used on arrays to enumerate the actual members of the array instead of just the items in the array. </p>
<h2 id="conclusion">Conclusion</h2>
<p>That's all for the <code>foreach</code> statement for the moment.  I do intend on addition support for something like <code>IEnumerable&lt;T&gt;</code> and <code>yield return</code> but not just yet...</p>
<p>If you've been using the experimental build of Prefix, I haven't updated it with this functionality yet - I'll post something when I do.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/135/Prefix-ForEach-Statements</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/135/Prefix-ForEach-Statements</guid>
			<comments>http://www.toptensoftware.com/Articles/135/Prefix-ForEach-Statements</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - Anonymous Functions and Lambdas</title>
			<author>brobinson</author>
			<pubDate>Mon, 26 Sep 2011 04:44:52 GMT</pubDate>
			<description><![CDATA[<p>A day or two ago I wrote about Prefix' support for delegates types - which are great, but they're only half the story.  To make the most of them, you really need anonymous functions and lambda expressions.</p>
<p><em>This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>A delegate type lets you declare the required prototype of function and pass references to matching functions around.  What we need now is an easier way to declare these functions inline - without having to create an actual &quot;function&quot; per se.  
</p>
<h3 id="anonymous-functions">Anonymous Functions</h3>
<p>An anonymous function is a function declared without a name and with an inferred return type.  It's declared using the <code>delegate</code> keyword as part of an expression.  Consider the following where an unnamed (&quot;anonymous&quot;) function is passed to a another function:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

void DoSomething(Func&lt;int, int&gt; cb)
{
    Console.WriteLine(cb(10));
}

DoSomething(delegate(int x) { return x*88; });
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function DoSomething(cb)
{
    Console.WriteLine(cb(10));
};

// Start Global Code
DoSomething(function(x) {
    return x*88;
});

})();
</code></pre>
</div>
<p>Because anonymous functions don't declare a return type, the compiler must be able to infer it from usage.  (in the above example it's infered from <code>DoSomething</code>'s <code>cb</code> parameter which is declared as <code>Func&lt;int, int&gt;</code></p>
<h3 id="lambda-expressions">Lambda Expressions</h3>
<p>Lambda expressions are an even more concise way of writing an anonymous function that directly returns the result of a single expression.  The syntax for lambda expressions is based around the <code>=&gt;</code> operator and prefix supports the same syntax formats as C#.  eg:</p>
<ul>
<li><code>()=&gt;99</code> - a lambda expression with no parameters</li>
<li><code>x=&gt;x*2</code> - a lambda expression with a single untyped parameter</li>
<li><code>(x,y)=&gt;x*y</code> - a lambda expression with multiple untyped parameters</li>
<li><code>(int x, int y)=&gt;x*y</code> - a lambda expression with multiple typed parameters</li>
</ul>
<p>A lambda expression is equivalent to a anonymous function that simply returns a value.  So this:</p>
<pre><code>(int x, int y) =&gt; x * y
</code></pre>
<p>is equivalent to:</p>
<pre><code>delegate(int x, int y) { return x * y; }
</code></pre>
<p>Note too that with lambda expressions (unlike anonymous functions) you don't have to specify type arguments for the parameters - they're inferred in the same way the return type is.</p>
<h3 id="solving-the--conundrum">Solving the <code>this</code>/<code>that</code> Conundrum</h3>
<p>In JavaScript when nesting one function inside another, the inner function doesn't inherit the <code>this</code> reference from the outer function.  In order to reference the outer class the developer must manually setup a <code>that</code> reference in the enclosing closure. (see <a href="http://javascript.crockford.com/private.html" target="_blank">here</a> for a better explanation).</p>
<p>The Prefix compiler however has enough type information to know how to set this up automatically.  So if an anonymous function inside a class method refers to a member variable of the outer class, <code>this</code> is automatically stored in a local variable <code>$this</code> and the nested function automatically uses it.</p>
<p>Here's an example showing both a lambda expression and the use of <code>$this</code>:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class MyClass
{
    public int Value;
    public void DoSomething(int input)
    {
        Func&lt;int, int&gt; fn = x=&gt;Value * x;
        Console.WriteLine(fn(input));
    }
}

var x = new MyClass();
x.Value = 23;
x.DoSomething(10);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// class MyClass
var MyClass = function() {};
MyClass.typeName = 'MyClass';
MyClass.prototype.Value = 0;

MyClass.prototype.DoSomething = function(input)
{
    var $this = this;
    var fn=function(x) { return $this.Value*x; };
    Console.WriteLine(fn(input));
};

// Start Global Code
var x=new MyClass();
x.Value = 23;
x.DoSomething(10);

})();
</code></pre>
</div>
<h3 id="generic-type-inference">Generic Type Inference</h3>
<p>All that's left to do in this area is type inference of generic function arguments from lambda's and anonymous functions - coming soon!</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/134/Prefix-Anonymous-Functions-and-Lambdas</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/134/Prefix-Anonymous-Functions-and-Lambdas</guid>
			<comments>http://www.toptensoftware.com/Articles/134/Prefix-Anonymous-Functions-and-Lambdas</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - typeof and typename operators</title>
			<author>brobinson</author>
			<pubDate>Mon, 26 Sep 2011 03:56:24 GMT</pubDate>
			<description><![CDATA[<p>Prefix does not (and will not) have an equivalent to .NET's runtime reflection capabilities.  It does however have something a little better than what JavaScript provides - introducing the <code>typename</code> and <code>typeof</code> operators...</p>
<p><em>This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>I've always thought JavaScript's runtime type support to be rather lame - not so much in what it can provide, but simply that it's rather inconsistent.  For example, using <code>typeof</code> on any custom class/object simply yields &quot;object&quot;.  Great - not.</p>
<p>In Prefix I wanted to improve this situation a little and provide something a little more reliable.  Prefix has two type inspection operators:  
</p>
<dl>
<dt><code>typeof</code></dt>
<dd>returns the constructor of an object or value</dd>
<dt><code>typename</code></dt>
<dd>returns a descriptive name for an object type</dd>
</dl>
<p>Both operators can accept either an object instance, or a compile type type name.  
</p>
<p>For the built in types (boolean, string etc...), <code>typeof</code> returns the boxed object constructor (eg: String.constructor) while <code>typename</code> returns the equivalent of the JavaScript <code>typeof</code> operator (eg: &quot;string&quot;, &quot;boolean&quot;, &quot;number&quot; etc....)</p>
<p>For Prefix classes, including generic classes <code>typeof</code> returns the class function and <code>typename</code> returns a descriptive name of the class - with generic arguments substituted.  eg:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class Bar
{
}

class MyClass&lt;T&gt;
{
    public void fn()
    {
        Console.WriteLine(typename(T));
    }
}

new MyClass&lt;bool&gt;().fn();
new MyClass&lt;int&gt;().fn();
new MyClass&lt;Bar&gt;().fn();
new MyClass&lt;MyClass&lt;int&gt;&gt;().fn();
Console.WriteLine(typename(MyClass&lt;int&gt;));
</code></pre>
<pre><code>boolean
number
Bar
MyClass&lt;&gt;[number]
MyClass&lt;&gt;[number]
</code></pre>
</div>
<p>Note that although Prefix distinguished between <code>int</code> and <code>double</code> at compile time, there is no such distinction at runtime - hence the appearance <code>number</code> in the resulting typename.</p>
<p>There are a couple of runtime helper functions to support these operators but as always they're tiny, automatically generated by the compiler and only generated when actually needed.</p>
<p>(Don't forget Prefix also supports runtime type querying via the <code>is</code> and <code>as</code> keywords).</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/133/Prefix-typeof-and-typename-operators</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/133/Prefix-typeof-and-typename-operators</guid>
			<comments>http://www.toptensoftware.com/Articles/133/Prefix-typeof-and-typename-operators</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Porting &quot;Burst Fish&quot; to Prefix</title>
			<author>brobinson</author>
			<pubDate>Sun, 25 Sep 2011 08:05:24 GMT</pubDate>
			<description><![CDATA[<p>A couple of days ago I stumbled on this great little JavaScript game tutorial and I thought it would be interesting to port it to Prefix as an example of something a little more &quot;real world&quot; than the hundreds of unit tests I've been using.</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>Burst Fish is a tutorial game written by Seb Lee-Delisle that I found on the excellent <a href="http://creativejs.com" target="_blank">creativejs.com</a> site.  The original tutorial can be found here <a href="http://creativejs.com/tutorials/create-an-ipad-optimised-game/" target="_blank">http://creativejs.com/tutorials/create-an-ipad-optimised-game/</a>.</p>
<div class="figure">
<img src="http://www.toptensoftware.com/Files/fishies.jpg?maxw=900" alt="fishies.jpg" width="600" height="300" />
</div>
<p>I thought this would be an excellent project to port to Prefix as both an example project and as a first experiment to see how Prefix works in the real world.  Aside from one missing piece of functionality and a few bugs in the compiler itself, porting it went remarkably well.  Here it is:</p>
<ul>
<li><a href="http://www.toptensoftware.com/prefix/samples/BurstGame/Burst.html">View the Game in your Browser</a> (You'll need a webkit based browser - Chrome or Safari)</li>
<li><a href="http://www.toptensoftware.com/downloads/BurstGame.zip">Download the Source</a></li>
</ul>
<p>(Please note I haven't released Prefix yet so although you can look at the source you can't compile it yourself yet.  If you're interested in trying the compiler ping me on Twitter or email me).</p>
<p>To show how the Prefix code looks, here's an extract of the <code>Emitter</code> class used to generate the exploding fish particles:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>// Emitted is used to generate the explosion particles
class Emitter
{
    // Constructor
    public Emitter(dynamic domContainer)
    {
        this.domContainer = domContainer;
    }

    // Fields
    private dynamic domContainer;
    private Particle[] _particles = new Particle[];
    private Particle[] _spareParticles = new Particle[];

    // Called by main game loop to update particules
    public void update()
    {
        for (var i=0; i&lt;_particles.length; i++)
        {
            var particle = _particles[i]; 
            if (!particle.update())
            {
                _spareParticles.push(particle);
            }
        }
    }

    // Make an explosion at specified position
    public void makeExplosion(double xpos, double ypos, double zpos)
    {
        // Just create bunch of particles
        for (var i=0; i&lt;30; i++)
        {
            var particle = makeParticle();
            particle.init(xpos, ypos, zpos);
            particle.update(); 
        }
    }

    // Make a particle by initializing a new one, or by grabbing one from 
    // the spare list
    private Particle makeParticle()
    {
        Particle particle;
        if (_spareParticles.length&gt;0)
        {
            particle = _spareParticles.shift();
        }
        else
        {
            particle = new Particle(domContainer); 
            _particles.push(particle); 
        }

        return particle; 
    }

}
</code></pre>
<pre class="prettyprint lang-javascript"><code>// class Emitter
var Emitter = function()
{
    this._particles = [];
    this._spareParticles = [];
};
Emitter.typeName = 'Emitter';
Emitter.prototype.domContainer = null;
Emitter.prototype._particles = null;
Emitter.prototype._spareParticles = null;

Emitter.prototype.ctor$1 = function(domContainer)
{
    Emitter.call(this);
    this.domContainer = domContainer;
    return this;
};

Emitter.prototype.update = function()
{
    for (var i=0; i&lt;this._particles.length; i++)
    {
        var particle=this._particles[i];
        if (!particle.update())
        {
            this._spareParticles.push(particle);
        }
    }
};

Emitter.prototype.makeExplosion = function(xpos, ypos, zpos)
{
    for (var i=0; i&lt;30; i++)
    {
        var particle=this.makeParticle();
        particle.init(xpos, ypos, zpos);
        particle.update();
    }
};

Emitter.prototype.makeParticle = function()
{
    var particle;
    if (this._spareParticles.length&gt;0)
    {
        particle = this._spareParticles.shift();
    }
    else
    {
        particle = (new Particle().ctor$1(this.domContainer));
        this._particles.push(particle);
    }
    return particle;
};

</code></pre>
</div>
<p>The game works as well as the original and although there are a few bits in the generated code that could be cleaned up, as a first attempt I'm fairly pleased with it.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/132/Porting-Burst-Fish-to-Prefix</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/132/Porting-Burst-Fish-to-Prefix</guid>
			<comments>http://www.toptensoftware.com/Articles/132/Porting-Burst-Fish-to-Prefix</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - Delegates</title>
			<author>brobinson</author>
			<pubDate>Sun, 25 Sep 2011 07:25:16 GMT</pubDate>
			<description><![CDATA[<p>In JavaScript, functions are &quot;first-class objects&quot; that can be stored in variables or passed as arguments to other functions.  Prefix delegates are similar except they're strongly typed.</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<p>&quot;First-class Functions&quot; are one of those topics that most new programmers struggle with - it's a weird concept passing a function to another function, or storing it in a variable.  In JavaScript however this is a fairly common practice and the Prefix equivalent is a delegate.</p>
<h2 id="simple-delegates">Simple Delegates</h2>
<p>A delegate type declaration gives a name to a function prototype ie: the set of parameters to a function and its return type.  Once a delegate type is declared you can create variables or parameters of that type and store or pass function references in them.</p>
<p>eg:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

// This is the delegate type - it specifies that functions
// references by it must have a single integer paramter and
// a void return type
delegate void delDoSomethingWithInt(int a);

// Here's a function that satisfies that requirement
void PrintInt(int x)
{
    Console.WriteLine(x.toString());
}

// Create a variable and store a reference to the function in it
delDoSomethingWithInt fn = PrintInt;

// Call it
fn(5);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function PrintInt(x)
{
    Console.WriteLine(x.toString());
};

// Start Global Code
var fn=PrintInt;
fn(5);

})();
</code></pre>
</div>
<p>Note that in the generated JavaScript all references to the delegate type vanish - however they've served there purpose in letting the compiler check that only matching functions are passed.  For example if the <code>PrintInt</code> function accepted a different set of parameters an error would be generated.</p>
<h2 id="binding-delegates-to-an-object-reference">Binding Delegates to an Object Reference</h2>
<p>In the above example, the function called is a simple global scope function.  Delegates however can reference a function on a specific object instance.  In this case, Prefix binds the object reference so that it's passed to the function correctly when it's invoked:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class MyClass
{
    public int Value;
    public void DoSomething()
    {
        Console.WriteLine(&quot;MyClass.DoSomething - &quot; + Value.toString());
    }
}

delegate void del();

var inst = new MyClass();
inst.Value=23;

del fn = inst.DoSomething;
fn();
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Prefix runtime library
var $dex = {};
$dex.bind=function(a,b){var c=a[b];return function(){c.apply(a,arguments)}} 

// class MyClass
var MyClass = function() {};
MyClass.typeName = 'MyClass';
MyClass.prototype.Value = 0;

MyClass.prototype.DoSomething = function()
{
    Console.WriteLine(&quot;MyClass.DoSomething - &quot; + this.Value.toString());
};

// Start Global Code
var inst=new MyClass();
inst.Value = 23;
var fn=$dex.bind(inst, &quot;DoSomething&quot;);
fn();

})();
</code></pre>
</div>
<p>Note that calling the delegate variable <code>fn</code> knows nothing of the <code>MyClass</code> instance, yet calling it still works thanks to the binding done by the helper function <code>$dex.bind</code>.</p>
<h2 id="generic-delegates">Generic Delegates</h2>
<p>Prefix also supports generic delegates.  Consider this example which is identical to the previous example except that the delegate is declared as a generic.  The <code>int</code> parameter type isn't resolved until the delegate is used:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class MyClass
{
    public int Value;
    public void DoSomething(int param)
    {
        Console.WriteLine(&quot;MyClass.DoSomething - &quot; + Value.toString() + &quot; - &quot; + param.toString());
    }
}

delegate void del&lt;T&gt;(T a);

var inst = new MyClass();
inst.Value=23;

del&lt;int&gt; fn = inst.DoSomething;
fn(5);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Prefix runtime library
var $dex = {};
$dex.bind=function(a,b){var c=a[b];return function(){c.apply(a,arguments)}} 

// class MyClass
var MyClass = function() {};
MyClass.typeName = 'MyClass';
MyClass.prototype.Value = 0;

MyClass.prototype.DoSomething = function(param)
{
    Console.WriteLine(&quot;MyClass.DoSomething - &quot; + this.Value.toString() + &quot; - &quot; + param.toString());
};

// Start Global Code
var inst=new MyClass();
inst.Value = 23;
var fn=$dex.bind(inst, &quot;DoSomething&quot;);
fn(5);

})();
</code></pre>
</div>
<h2 id="and-"><code>Func</code> and <code>Action</code></h2>
<p>Now that Prefix has support for generic delegates, support for <code>Func</code> and <code>Action</code> are simply a matter of declaring them:</p>
<pre class="prettyprint lang-csharp"><code>delegate TResult Func&lt;TResult&gt;();
delegate TResult Func&lt;T1, TResult&gt;(T1 p1);
delegate TResult Func&lt;T1, T2, TResult&gt;(T1 p1, T2 p2);
// etc...

delegate void Action();
delegate void Action&lt;T1&gt;(T1 p1);
delegate void Action&lt;T1, T2&gt;(T1 p1, T2 p2);
// etc...
</code></pre>
<p>Prefix includes built-in declarations for Func and Action with up to 8 parameters:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;


int addem(int a, int b)
{
    return a+b;
}

Func&lt;int, int, int&gt; op = addem;

Console.WriteLine(op(10, 20).toString());
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function addem(a, b)
{
    return a + b;
};

// Start Global Code
var op=addem;
Console.WriteLine(op(10, 20).toString());

})();
</code></pre>
</div>
<h2 id="type-inference-with-delegates">Type Inference with Delegates</h2>
<p>Prefix supports generic type inference with delegates.  The following example declares a generic function with two generic parameters <code>TIn</code> and <code>TOut</code>.  Note that when the function is called, it's simply called <code>fn</code> and the type are inferred from the usage.  ie: Prefix has inferred that <code>TIn</code> is <code>int</code> and <code>TOut</code> is <code>string</code>.</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

TOut fn&lt;TIn, TOut&gt;(Func&lt;TIn,TOut&gt; cb, TIn input)
{
    return cb(input);
}

string convert(int val)
{   
    return val.toString();
}

Console.WriteLine(fn(convert, 23));
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function fn$2(cb, input)
{
    return cb(input);
};

function convert(val)
{
    return val.toString();
};

// Start Global Code
Console.WriteLine(fn$2(convert, 23));

})();
</code></pre>
</div>
<h2 id="conclusion">Conclusion</h2>
<p>Delegates are an important concept for Prefix as they bring the language considerably closer to JavaScript's capabilities and also lead into Lambda's and Anonymous Functions which I'm working on now.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/131/Prefix-Delegates</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/131/Prefix-Delegates</guid>
			<comments>http://www.toptensoftware.com/Articles/131/Prefix-Delegates</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - Arrays</title>
			<author>brobinson</author>
			<pubDate>Tue, 20 Sep 2011 01:14:58 GMT</pubDate>
			<description><![CDATA[<p>Prefix now supports arrays and starts to diverge from C#/.NET a little...</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<h2 id="arrays">Arrays</h2>
<p>The recent focus with Prefix has been to get to the point where it can support JavaScript arrays. As mentioned in my previous post this involved support for generics, indexers, readonly properties and variadic parameters.  What I didn't mention is that although I've added support for compiling all these features from Prefix to JavaScript, for arrays I only needed the ability to declare these constructs - since JavaScript provides the actual array implementation.</p>
<p>Arrays in Prefix are a little different to C# arrays.  First, they're implemented as a generic class - <code>Array&lt;T&gt;</code>, as opposed to a type handled in the language itself.  Second, since they wrap up the JavaScript array class they can be resized and behave more like a C# List.</p>
<p>So here's the built in declaration of the Array class:</p>
<pre class="prettyprint lang-csharp"><code>extern class Array&lt;T&gt; : Object
{
    extern readonly int length;
    extern T this[int index] { get; set; }
    extern string join();
    extern string join(string separator);
    extern T pop();
    extern int push(T x);
    extern void reverse();
    extern T shift();
    extern int unshift(T x);
    extern Array&lt;T&gt; slice(int start);
    extern Array&lt;T&gt; slice(int start, int end);  
    extern Array&lt;T&gt; splice(int index, int howmany);
    extern Array&lt;T&gt; splice(int index, int howmany, T insert);
    extern Array&lt;T&gt; concat(Array&lt;T&gt; other_array);
    extern Array&lt;T&gt; concat(params Array&lt;Array&lt;T&gt;&gt; arrays);
    extern int push(params T[] x);
    extern int unshift(params T[] x);
    extern Array&lt;T&gt; splice(int index, int howmany, params T[] insert);
}
</code></pre>
<p>It simply declares the standard array manipulation functions. You'll notice there's no declaration for <code>indexOf</code> - since it's not supported in IE's JavaScript engine - I still need to figure out a nice way to normalize those sorts of quirks.</p>
<p>Although the <code>Array</code> type is a generic class the compiler also supports some syntactic sugar to make it look more traditional - any type suffixed with <code>[]</code> gets converted to an array generic.  eg: <code>string[]</code> is identical to <code>Array&lt;string&gt;</code></p>
<p>Using the array class is pretty much as you'd expect and looks very similar to standard JavaScript:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

var x = new string[];
x.push(&quot;Hello&quot;);
x.push(&quot;World&quot;);
x.splice(1, 0, &quot;There&quot;);

for (int i=0; i&lt;x.length; i++)
    Console.WriteLine(x[i]);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Start Global Code
var x=[];
x.push(&quot;Hello&quot;);
x.push(&quot;World&quot;);
x.splice(1, 0, &quot;There&quot;);
for (var i=0; i&lt;x.length; i++)
    Console.WriteLine(x[i]);

})();
</code></pre>
</div>
<p>Note:</p>
<ul>
<li>instantiating a new array instance (<code>new string[]</code>) gets re-compiled into just <code>[]</code> (as any self-respecting JavaScript programmer would expect).</li>
<li>there's no size argument when instantiating an array (as opposed to C#)</li>
<li>even though the generated code looks almost exactly like the original the real benefit here is all the error checking the compiler is doing for you.</li>
<li>you can escape the type safety and revert to the wild world of dynamic with <code>dynamic[]</code> - which is essentially an untyped JavaScript array.</li>
<li>Prefix doesn't yet support the <code>foreach</code> statement, so enumerating an array is currently limited to an integer indexer. Collection enumeration via <code>foreach</code> will be coming soon.</li>
</ul>
<h2 id="what-about-.nets--class">What About .NET's <code>List&lt;T&gt;</code> Class?</h2>
<p>It's at this point that I thought I'd be providing a compatible implementation of C#/.NET's <code>List&lt;T&gt;</code> class.  After a lot of consideration though I felt this was the wrong approach - re-implementing the .NET runtime is <em>not</em> the point of this project.  
</p>
<p>There are a few cases where it would be great to compile the same code base under both C# and Prefix.  Rather than trying to provide a Prefix implementation of many of the common .NET library functions I'm thinking of doing the opposite - providing a C# implementation of the Prefix runtime.</p>
<p>Of course if you really need <code>List&lt;T&gt;</code> you could always re-implement it yourself in Prefix code.</p>
<h2 id="next-up">Next Up</h2>
<p>I'm currently working on delegate support and have it mostly working - the current stumbling block is getting generic function type inference working with generic delegate parameters... but more about that later.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/130/Prefix-Arrays</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/130/Prefix-Arrays</guid>
			<comments>http://www.toptensoftware.com/Articles/130/Prefix-Arrays</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix - Generics (again), indexers, read only fields, variadic parameters</title>
			<author>brobinson</author>
			<pubDate>Fri, 16 Sep 2011 01:09:19 GMT</pubDate>
			<description><![CDATA[<p>In this last week or so I've been working on getting Prefix to the point where arrays are working.  Unfortunately this highlighted a couple of design flaw in generics...</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<h2 id="infinitely-recursive-generic-types">Infinitely Recursive Generic Types</h2>
<p>In my previous post I suggested that I had generics working.  Well not quite and I've had to do a major reworking of it. The first problem was that with generics it's possible to have an infinitely recursive type definition.  Consider this example:</p>
<pre class="prettyprint lang-csharp"><code>class MyClass&lt;T&gt;
{
    MyClass&lt;MyClass&lt;T&gt;&gt; SomeFunction();
}
</code></pre>
<p>Now imagine you create the closed type <code>MyClass&lt;int&gt;</code>.  The return value from the function will be <code>MyClass&lt;MyClass&lt;int&gt;&gt;</code> - but that type has a <code>SomeFunction</code> method that returns <code>MyClass&lt;MyClass&lt;MyClass&lt;int&gt;&gt;&gt;</code>.  And so on...</p>
<p>Prefix's original generic implementation tried to fully close generic types as soon as they were used - so the above immediately crashed with a stack overflow exception as it recursively tried to make those closed types.</p>
<p>Of course the fix was simple once I understood it - just delay making those closed types until needed.</p>
<p>You'd think the above is a weird edge case that would never happen. Ironically it cropped up almost the first time I tried to use generics (to declare Prefix's array class).</p>
<h2 id="nested-generics-might-not-be-what-you-think">Nested Generics Might Not Be What You Think</h2>
<p>Probably the most difficult part of getting generics working was nested generic classes - that is until I understood what they really are (not what I thought they were).  Originally I presumed that on making a closed generic class any inner nested classes would become part of that newly generated closed class.</p>
<p>However that is not the case - at least when you look at how C# does it.  In C# a nested generic class is simply a generic class that inherits the same set of generic parameters as the outer class and tacks its own generic parameter on the end.</p>
<p>So this class:</p>
<pre class="prettyprint lang-csharp"><code>class Outer&lt;T&gt;.Inner&lt;U&gt;
</code></pre>
<p>is really implemented as:</p>
<pre class="prettyprint lang-csharp"><code>class Outer.Inner&lt;T,U&gt;
</code></pre>
<p>Discovering this helped solve a whole class of problems with generics but required a fair bit of reworking the code - though pleasingly the generated JavaScript is now simpler and slightly smaller.</p>
<h2 id="read-only-fields">Read Only Fields</h2>
<p>Now that generics were working properly, I was at the point that I could start looking at what else was required to get arrays working.  First up was <code>readonly</code> fields (since the <code>length</code> property of an array should be readonly).</p>
<p>Read only fields work identically to C# readonly fields.  They can be initialized via a direct initializer or in the class constructor.  
</p>
<pre class="prettyprint lang-csharp"><code>class Foo
{
    public Foo()
    {
        val=&quot;Hello World&quot;;
    }

    public readonly string val;
}
</code></pre>
<p>I haven't included the generated JavaScript code here because the enforcement of <code>readonly</code>-ness is done at compile time - not runtime.  You could get around this by casting to a <code>dynamic</code> if you really wanted.</p>
<h2 id="indexers">Indexers</h2>
<p>Arrays are fairly useless without indexers.  Indexers are implemented like properties with parameters.  Just like C# they can be overloaded, but Prefix doesn't support variadic (parameter array) indexers.  In JavaScript they're implemented as methods <code>$get_at</code> and <code>$set_at</code>.</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class Foo
{
    public string this[int index]
    {
        get
        {
            Console.WriteLine(&quot;get[&quot; + index.toString() + &quot;]&quot;);
            return index.toString();
        }
        set
        {
            Console.WriteLine(&quot;set[&quot; + index.toString() + &quot;] = &quot; + value);
        }
    }
}

var f = new Foo();
Console.WriteLine(f[99]);
f[99]=&quot;newval&quot;;
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// class Foo
var Foo = function() {};
Foo.typeName = 'Foo';

Foo.prototype.$get_at = function(index)
{
    Console.WriteLine(&quot;get[&quot; + index.toString() + &quot;]&quot;);
    return index.toString();
};

Foo.prototype.$set_at = function(index, value)
{
    Console.WriteLine(&quot;set[&quot; + index.toString() + &quot;] = &quot; + value);
    return value;
};

// Start Global Code
var f=new Foo();
Console.WriteLine(f.$get_at(99));
f.$set_at(99, &quot;newval&quot;);

})();
</code></pre>
</div>
<h2 id="variadic-parameters">Variadic Parameters</h2>
<p>The JavaScript array class supports passing a variable number of arguments to some of it's methods - commonly called variadic functions.  
</p>
<p>In C# variadic methods can be called in two ways - normal form and expanded form.  For example, this function:</p>
<pre class="prettyprint lang-csharp"><code>int Sum(params int[] values);
</code></pre>
<p>can be called like this:</p>
<pre class="prettyprint lang-csharp"><code>// Expanded form
Sum(1,2,3,4);
</code></pre>
<p>or by passing an array directly:</p>
<pre class="prettyprint lang-csharp"><code>// Normal form
var values = new int[] { 1, 2, 3, 4 };
Sum(values);
</code></pre>
<p>To replicate this in JavaScript, if the passed variable is an array it's assumed to be a normal form call and used directly, otherwise the JavaScript <code>arguments</code> are sliced to create an array.</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

int sum(int first, params int[] other)
{
    for (int i=0; i&lt;other.length; i++)
    {
        first += other[i];
    }
    return first;
}

Console.WriteLine(sum(1,2,3,4));
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

function sum(first, other)
{
    if (!(other instanceof Array)) other = Array.prototype.slice.call(arguments, 1);
    for (var i=0; i&lt;other.length; i++)
    {
        first += other[i];
    }
    return first;
};

// Start Global Code
Console.WriteLine(sum(1, 2, 3, 4));

})();
</code></pre>
</div>
<p>Of course using this technique to detect whether the function is being called in normal or expanded form doesn't work for arrays of arrays (since there isn't enough type information in JavaScript at runtime) to work this out.  In this case Prefix disallows the short form calling and generates an error.</p>
<p>Actually, Prefix does a slightly better job than shown above.  If the target function is never called in short form, the <code>if</code> statement is omitted and <code>arguments</code> is sliced directly.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I now have everything to get arrays working... which I'll talk about in the next post.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/129/Prefix-Generics-again-indexers-read-only-fields-variadic-parameters</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/129/Prefix-Generics-again-indexers-read-only-fields-variadic-parameters</guid>
			<comments>http://www.toptensoftware.com/Articles/129/Prefix-Generics-again-indexers-read-only-fields-variadic-parameters</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Prefix takes One Giant Leap with Support for Generics</title>
			<author>brobinson</author>
			<pubDate>Tue, 6 Sep 2011 05:51:20 GMT</pubDate>
			<description><![CDATA[<p>After a week or so of mind melting work, Prefix now support Generics!  This was a challenge both in compiling the Prefix code and in working out how to generate the required JavaScript.  But since there's not much point to a strongly typed language without strongly typed collections, I'm sure the effort is worth it...</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<h2 id="what-are-generics">What Are Generics?</h2>
<p>For this post I'm going to assume you're already familiar with C#'s generic support.  If you're not, there are plenty of references and tutorials available online (<a href="http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx" target="_blank">here's one from Microsoft</a>).  In short generics are a way to declare strongly typed classes, interfaces and methods that defer the specification of one or more types until the class or method is used in code</p>
<h2 id="generics-in-prefix">Generics in Prefix</h2>
<p>Prefix's supports most of the C# generics capabilities including:</p>
<ul>
<li>multiple type parameter</li>
<li>constraints -  base class, required interfaces, <code>new()</code> and <code>class</code></li>
<li>generic classes, intefaces and methods</li>
<li>nested generic types</li>
<li>parameter type inference for generic functions</li>
</ul>
<p>To support this functionality there's up to about 1.5kb of automatically embedded and minified runtime code.  In many cases however generics can be used with no runtime library requirements - in which case the Prefix compiler will leave it out.</p>
<h2 id="a-simple-generic-class">A Simple Generic Class</h2>
<p>Here's an example of a simple generic list class: (see further down for notes)</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>// no warnings
extern dynamic Console;

class MyList&lt;T&gt;
{
    public void Add(T t)
    {
        _data.push(t);
    }

    public T GetAt(int index)
    {
        return (T)(`this._data[index]`);
    }

    public int Count
    {
        get
        {
            return _data.length;
        }
    }

    T[] _data = (T[])(`[]`);
}

var l = new MyList&lt;int&gt;();
Console.WriteLine(l.Count);
l.Add(10);
l.Add(20);
l.Add(30);
Console.WriteLine(l.Count);

for (int i=0; i&lt;l.Count; i++)
{
    Console.WriteLine(l.GetAt(i));
}
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// class MyList&lt;T&gt;
var MyList$1 = function()
{
    this._data = [];
};
MyList$1.typeName = 'MyList$1';
MyList$1.prototype._data = null;

MyList$1.prototype.Add = function(t)
{
    this._data.push(t);
};

MyList$1.prototype.GetAt = function(index)
{
    return this._data[index];
};

MyList$1.prototype.get_Count = function()
{
    return this._data.length;
};

// Start Global Code
var l=new MyList$1();
Console.WriteLine(l.get_Count());
l.Add(10);
l.Add(20);
l.Add(30);
Console.WriteLine(l.get_Count());
for (var i=0; i&lt;l.get_Count(); i++)
{
    Console.WriteLine(l.GetAt(i));
}

})();

</code></pre>
</div>
<p>Note the following:</p>
<ul>
<li>The JavaScript class name is qualified with the number of type arguments (ie: <code>MyList$1</code>). This is because its possible to have multiple generic classes, each with a different number of generic arguments.  <code>MyList&lt;T,U&gt;</code> would be converted to <code>MyList$2</code> etc...</li>
<li>Arrays are implemented as a new built-in system generic <code>Array&lt;T&gt;</code>.  Unlike C# arrays but like JavaScript arrays, Prefix arrays can be resized after being created.</li>
<li>Since I don't have complete language level operability with JavaScript arrays yet, I've had to resort to using backtick escapes to get this example to work. (see <code>GetAt</code> and the <code>_data</code> initializer in the Prefix code.)</li>
<li>There's no runtime overhead with this example - all type checking is done at compile time.</li>
</ul>
<h2 id="an-example-with-runtime-dependencies">An example with Runtime Dependencies</h2>
<p>As in the above example, many generic types - especially collection classes - don't require any runtime type information about the generic type arguments and therefore translate fairly cleanly to JavaScript.    When you do need runtime type information things get more complicated, but I've tried to hide away the messy details as much as possible.</p>
<p>Consider this example that can create instances of a type declared through a generic parameter:</p>
<div class="sxs">
<pre class="prettyprint lang-csharp"><code>extern dynamic Console;

class Foo
{

}

class MyFactory&lt;T&gt; where T:new()
{
    public T CreateInstance()
    {
        return new T();
    }
}

var foo = new MyFactory&lt;Foo&gt;().CreateInstance();
Console.WriteLine(foo is Foo);
</code></pre>
<pre class="prettyprint lang-javascript"><code>(function() {

// Prefix runtime library
var $dex = {};
$dex.makeCachedGeneric=/* removed */ 
$dex.resolveGenericArg=/* removed */
$dex.resolveGenericArgs=/* removed */
$dex.setupGenericClass=/* removed */

// class Foo
var Foo = function() {};
Foo.typeName = 'Foo';

// class MyFactory&lt;T&gt;
var MyFactory$1 = $dex.setupGenericClass(1, null, null, null, function() {});
MyFactory$1.typeName = 'MyFactory$1';

MyFactory$1.prototype.CreateInstance = function()
{
    var T = this.closedClass$1.genericArgs[0];
    
    return new T();
};

// Start Global Code
var foo=(new (MyFactory$1.makeGeneric([Foo]))()).CreateInstance();
Console.WriteLine((foo)!==null);

})();
</code></pre>
</div>
<p>Note:</p>
<ul>
<li>I've removed the runtime library functions because they're messy and distract from the interesting stuff.</li>
<li>The <code>MyFactory$1</code> class is initialized using the runtime function <code>setupGeneric</code> which does everything need to turn this into a generic class with runtime information about the generic args.</li>
<li><code>MyFactory&lt;Foo&gt;</code>  becomes  <code>MyFactory$1.makeGeneric([Foo])</code>.</li>
<li><code>makeGeneric</code> creates a new class (if not already created) that knows about <code>Foo</code> as the type argument</li>
<li>Inside <code>CreateInstance</code> you can see <code>T</code> is retrieved via a <code>this.closedClass$1</code> which is setup by the call to <code>makeGeneric</code>.</li>
</ul>
<p>As you can see, it's a little messy but quite powerful.  I've tried to make the JavaScript code mirror as closely as possible the original Prefix code - mainly it's the <code>makeGeneric</code> call that messes things up - everything else is reasonably out of the way.</p>
<p>This additional runtime code is required when:</p>
<ul>
<li>the generic class contains a <code>new T()</code></li>
<li>using dynamic casts (<code>as</code> and <code>is</code>) to/from <code>T</code></li>
<li>using <code>default(T)</code> and T is not known to be a reference type (ie: no <code>T</code> has no constraints)</li>
<li>A generic class has static fields (since each set of generic arguments gets its own copy of the variable)</li>
</ul>
<h2 id="more-examples">More Examples</h2>
<p>Rather than post detailed examples of everything here, feel free to checkout the latest <a href="http://www.toptensoftware.com/prefix/report.html">unit test results</a> for more detail.  There are examples of generic functions, generic classes with static members, nested generics and more.  If you're adventurous, the test cases also include the uncensored JavaScript with the runtime library support functions in all their gory detail.</p>
<p>In conclusion I've tried to make Prefix's generics support powerful but not at the expense of too much interference in the generated JavaScript code.  Although I'd like the JavaScript to be cleaner I'm not sure what else could be done to improve it.</p>
<p>Generics is a huge step forward for Prefix and paves the way for a number of other features including arrays and enumerating collections with <code>foreach</code> statements.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/128/Prefix-takes-One-Giant-Leap-with-Support-for-Generics</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/128/Prefix-takes-One-Giant-Leap-with-Support-for-Generics</guid>
			<comments>http://www.toptensoftware.com/Articles/128/Prefix-takes-One-Giant-Leap-with-Support-for-Generics</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item><item>
			<title>Unit Testing Prefix with V8, V8Sharp and PetaTest (and hints on what&#39;s coming next)</title>
			<author>brobinson</author>
			<pubDate>Tue, 30 Aug 2011 03:02:29 GMT</pubDate>
			<description><![CDATA[<p>In developing Prefix I needed a reliable, flexible and fast unit testing framework.  To build this I used V8 (Google's JavaScript Engine from Chrome), V8Sharp (a .NET wrapper for V8) and PetaTest (my tiny unit testing framework).</p>
<p><em>This post is about Prefix a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the <a href="http://www.toptensoftware.com/prefix">Prefix Project Page</a>.</em></p>
<h2 id="unit-testing-javascript">Unit Testing JavaScript</h2>
<p>This isn't the first time I've had to run JavaScript code for unit testing.  Previously what I've done is hosted the Microsoft Web Control, loaded a page with the appropriate JavaScript code and interoped to it through a Windows Form application.  This is how I implemented the unit tests for the JavaScript port of <a href="http://www.toptensoftware.com/markdowndeep">MarkdownDeep</a> - it works, but it's messy and very slow.  
</p>
<p>For Prefix, I wanted something better so I started looking around for a JavaScript engine that would be easy to host in .NET.  I knew about Google's V8 JavaScript engine so that seemed the obvious place to start.  I got it building and was about to start on some C++/CLR/IJW interop code for it when I stumbled upon <a href="http://v8sharp.codeplex.com/wikipage?title=Home&amp;ProjectName=v8sharp" target="_blank">V8Sharp</a> - which does exactly what I needed.</p>
<p>Hosting V8 with V8Sharp is trivial, here's the bit to run some JavaScript code:</p>
<pre class="prettyprint lang-csharp"><code>var v8 = v8sharp.V8Engine.Create();
v8.Register&lt;TestConsole&gt;(&quot;Console&quot;, console);
v8.Execute(jsActual);
</code></pre>
<p><code>TestConsole</code> is a simple class that V8Sharp makes available to the script and I use it to route text output to the Console:</p>
<pre class="prettyprint lang-csharp"><code>public class TestConsole
{
    public TestConsole()
    {
    }
    public void Write(object output)
    {
        Console.Write(output.ToString());
    }
    public void WriteLine(object output)
    {
        Console.WriteLine(output.ToString());
    }
}
</code></pre>
<p>So from JavaScript code I can now do this:</p>
<pre class="prettyprint lang-javascript"><code>Console.WriteLine(&quot;Hello World (from JavaScript)&quot;);
</code></pre>
<h2 id="building-the-rest-of-the-unit-testing-framework">Building the Rest of the Unit Testing Framework</h2>
<p>Next I brought V8 and V8Sharp together with <a href="http://www.toptensoftware.com/petatest">PetaTest</a>.  The unit test program has a single test fixture and a single parameterized test case.  That one test case loads one of many test scripts from an embedded resource (it could be an external file if necessary).  Currently I have about 350+ of these test scripts and I've setup PetaTest so that I can invoke one, all or a subset of tests - depending on what I'm working on.</p>
<h2 id="format-of-the-test-scripts">Format of the Test Scripts</h2>
<p>Each unit test script is a text file that looks like this:</p>
<pre><code>extern dynamic Console
Console.WriteLine(&quot;Hello World from Prefix&quot;);
----
Hello World from Prefix
</code></pre>
<p>The test script is divided into two sections separated by a dashed <code>----</code> delimiter.  The top half is the Prefix code to be compiled and executed.  The bottom half is the expected output.</p>
<h2 id="testing-error-reporting">Testing Error Reporting</h2>
<p>Of course a compiler needs to generate not just a correctly functioning output program, it should also generate errors when there are problems in the input program.  To test these, the expected output can specify an exception that should be generated. </p>
<p>eg:</p>
<pre><code>extern dynamic Console;

public enum MyEnum
{
    a,
    b,
    c,
}

MyEnum.a=12;

-----
// exception: The left hand side of an assignment must be a variable, property or indexer
</code></pre>
<p>In compiling this script the unit test will fail if the compiler doesn't generate an exception containing the specified text.</p>
<h2 id="closer-inspection-of-the-generated-javascript">Closer Inspection of the Generated JavaScript</h2>
<p>Usually the correctness of the generated script can be confirmed by examining the expected output.  There are cases however where I need to ensure that the correct output was generated in a particular way.  For this there are a couple of additional directives that can be embedded in the input script to ensure the generated script does or does not contain particular content.  
</p>
<pre><code>// should generate: Foo.prototype.str = &quot;OK&quot;;
// should not generate: this.str = 

extern dynamic Console;

class Foo
{
    public string str = &quot;OK&quot;;
} 

Console.WriteLine(new Foo().str);

-----
OK
</code></pre>
<p>Note the <code>should generate:</code> and <code>should not generate:</code> directives at the top of the script.</p>
<h2 id="compiler-options">Compiler Options</h2>
<p>Finally there are a few other directives that can be used to tweak how the Prefix compiler is invoked.</p>
<ul>
<li><code>// no warnings</code> - by default the test cases are run with warnings as errors (so warnings can be tested).  This option disables this.</li>
<li><code>// release mode</code> - run the compiler in release mode.</li>
</ul>
<p>(Note these are directives to the test case framework - not the actual Prefix compiler).</p>
<h2 id="example-output">Example output</h2>
<p>Here's the current set of unit test results.  Right now (late Aug 2011) there are about 350 unit tests, all passing except 1 - which I'm working on.</p>
<ul>
<li><a href="http://www.toptensoftware.com/prefix/report.html">Prefix Unit Test Results</a></li>
</ul>
<p>If you click on the name of a unit test it will expand to show the input Prefix program, the expected output, the generated  JavaScript and the results of the test.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I'm pretty happy with this testing environment.  It's fast - 350+ unit tests in under 2 seconds, flexible and I get a nice output report thanks to PetaTest - the linked report above is exactly what PetaTest generates - I haven't modified or re-formatted it in any way.</p>
]]></description>
			<link>http://www.toptensoftware.com/Articles/127/Unit-Testing-Prefix-with-V8-V8Sharp-and-PetaTest-and-hints-on-what-s-coming-next</link>
			<guid isPermaLink="false">http://www.toptensoftware.com/Articles/127/Unit-Testing-Prefix-with-V8-V8Sharp-and-PetaTest-and-hints-on-what-s-coming-next</guid>
			<comments>http://www.toptensoftware.com/Articles/127/Unit-Testing-Prefix-with-V8-V8Sharp-and-PetaTest-and-hints-on-what-s-coming-next</comments>
			<category>JavaScript</category>
			<category>Prefix</category>
			</item></channel>
</rss>		
