Wednesday, August 5, 2009

Worlds: Controlling the Scope of Side Effects

Worlds is "a language construct that reifies the notion of program state, and enables programmers to control the scope of side effects." Alessandro Warth investigaged this idea together with Alan Kay in a paper entitled Worlds: Controlling the Scope of Side Effects. Chapter 4 of Warth's dissertation Experimenting with Programming Languages obsoletes this paper. Worlds/JS is an extension of JavaScript implementing worlds.

The basic idea is to turn program state into first-class objects, allowing them to co-exist in the same program and enable them to inherit and delegate state to and from each other. Warth calls such a program state object a world. "All computation takes place inside a world, which captures all of the side effects [...] that happen inside it".

In Worlds/JS thisWorld "is an expression that evaluates to the current world and in expr block is a statement that executes block inside the world obtained by evaluating expr". Additionally a world object has two member functions, sprout and commit. sprout creates an new child world with the same initial state and copy-on-write semantics. commit copies the side-effects catched by the child back to the parent. Everything else is standard JavaScript.

The semantics of property lookup in the presence of worlds is formally defined in Warth's thesis. Besides normal scope rules the interesting part is that a missing property is first searched in parent worlds and then in parent objects.

With this few extensions you can create checkpoints, try something out and rollback the program's state if necessary. There are a number of examples in Warth's publications. Here is one of those:

w = thisWorld.sprout();
try {
  in w {
    for (var idx = 0; idx < xs.length; idx++)
} catch (e) {
  w = null;
  // ...
} finally {
  if (w != null)

The requirement is that all elements of xs should be updated. If any update fails the array should be reset to its initial state. Without worlds the catch block would have to undo all update operations done so far. With worlds the updates are done within a new child world w and either discarded in case of an exception or committed altogether.

Another very interesting application for worlds is OMeta where there exists the problem that side effects of semantic actions are not undone in case of backtracking. With worlds it is very easy to solve that problem by simply sprout new worlds for the evaluation of semantic actions and commit them only if the whole expression succeeds.

Thanks to Mike for pointing this topic out to me.

No comments:

Post a Comment