Friday, June 11, 2010

Designing a Core/Simplified JavaScript

I am working towards a core language for JavaScript... JavaScript by itself is nice for humans but not for compilers. The language definition has just one special case too many.

Here is a take on the Core:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
type UnaryOperator =
| TypeOf = 0
| Delete = 1
| BitwiseNot = 2

type BinaryOperator =
| Multiply = 0
| Divide = 1
| Modulo = 2
| Add = 3
| Subtract = 4
| LeftShift = 5
| SignedRightShift = 6
| UnsignedRightShift = 7
| LessThan = 8
| GreaterThan = 9
| Equal = 10
| Identical = 11
| InstanceOf = 12
| In = 13
| BitAnd = 14
| BitXor = 15
| BitOr = 16

type Primitive =
| Null
| Boolean of bool
| Integer of int64
| Double of double
| String of string
| Array of list<Expr>
| Object of list<string * Expr>
| Unary of UnaryOperator * Expr
| Binary of BinaryOperator * Expr * Expr
| New of Expr * list<Expr>
| Get of Expr * Expr
| Set of Expr * Expr * Expr
| Lookup of string
| Throw of Expr
| Try of Expr * Var * Expr
| While of Expr * Expr

And then expressions are instances of Core Scheme expressions instantiated with Primitive.

1
2
3
4
5
6
7
8
9
    type Expression<'T> =
| Assign of Var * Expression<'T>
| Apply of Expression<'T> * list<Expression<'T>>
| If of Expression<'T> * Expression<'T> * Expression<'T>
| Lambda of list<Id> * Expression<'T>
| Let of Id * Expression<'T> * Expression<'T>
| Var of Id
| Primitive of 'T
| Undefined

Notes:

  • No expression/statement distinction - this should be automated.

  • JavaScript calls are modelled with Apply where the first argument is always this argument. Therefore foo.bar(baz) becomes Apply (foo.[bar], foo :: baz).

  • Global variable references are modelled as Lookup, say window becomes Lookup "window".

  • LetRec clause, as in Scheme, is derived - it is modelled with Assign and Let.

  • Some JavaScript assignments are field assignments and not variable assignments - and these are a primitive, for example foo.bar = 1 becomes Set (foo, bar, 1).

  • No try-finally - can be reduced to Try.

  • No loops other than While - others can be reduced to it.

This seems to be expressive enough. I will probably update the definition after trying to write a few optimizations.

No comments:

Post a Comment