Hi! This blog is for news, announcements and questions regarding the
Mascara JavaScript compiler.

See also:
The online demo
Download latest release

Contact:
olav@olav.dk

Disclaimer:
ECMAScript is a trademark of Ecma International.

Powered by Squarespace
« Release 0.2.2 | Main | Version 0.1.8 released »
Tuesday
Jun172008

Version 0.2.0 released. With like.

Version 0.2.0 is now released. Download.
The major new feature is support for Like-constraints.
This is one of my favorite features. It allows us to declare what a parameter (or return value) should look like rather than what class it should be or descend from. This is a critical feature if we want to integrate classic JavaScript with typed ECMAScript 4 without having to rewrite everything at once.

Consider this. We have a point-type (with members x and y), and a function that operates on it:

var point1 = {x:10,y:20};
function sum(point) {
return point.x + point.y;
}

Now we might want to make the sum-function more type-safe. We could do that by declaring the structural type of the argument:

function sum(point : {x:int,y:int}) {
return point.x + point.y;
}

Now we are sure that no one accidentally call the functions with the wrong type of argument.
We could make it more explicit by defining a named type:

type Point = {x:int,y:int};
function sum(point : Point) {
return point.x + point.y;
}

So far so good. However now the type is constrained to only accept a record. A point could be expressed in other ways, eg. using a class:

class ClsPoint {
var x : int;
var y : int;
function ClsPoint(_x : int, _y : int)
: x=_x, y=_y {}
}
var point2 = new ClsPoint(10, 20);

or as a traditional JavaScript object:

function JsPoint(x : int, y : int) {
this.x = x;
this.y = y;
}
var point3 = new JsPoint(10, 20);

However, both of these will be rejected as arguments to sum, because they are not strictly of the same type as Point, which is declared as a record type.

"Like" to the rescue. If we define the function like this:

function sum(point like Point) {
return point.x + point.y;
}

The type system will check if the argument looks like Point, that is, has members with the same names and types as Point. Now all three types of objects will be accepted, since they all have the required x and y properties.

This is very cool, because it allows us to bridge the new classes, classic JavaScript constructors and pure structures (like what you get through JSON) in the same type system.

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>