Safe, Closure-free, Serializable functions

Tom Van Cutsem at
Fri Sep 27 09:59:56 PDT 2013

2013/9/27 David Herman <dherman at>

> ## Why environment-free closures is a bad idea
> [...]
> Third, I don't think it's sufficiently expressive. I'd be much more
> interested in seeing something along these lines:
> - the ability to define custom serialization logic (as opposed to, or
> perhaps in extension to, the ad hoc structured clone algorithm)
> - the ability to define serializable functions whose serialization logic
> lifts through their upvars

We've found the need for serializable functions in AmbientTalk, which, like
JS, encourages a style of programming that makes significant use of lexical
nesting. We have found that this programming style makes that requiring
serializable functions to be closed is indeed too restrictive. Translated
to JS, our solution looks like:

var z = 42;
var f = function(x,y) (z) {
  // x and y are locals, z refers to (a copy of) the upvar

Here, f is a pass-by-copy function. The second parameter list captures the
upvars that should be serialized together with the function. In the
function body, only x, y and z are in scope, and z refers to the original
upvar (when called on the original), or to a copied upvar (when called on a
deserialized copy of the function).

The benefit of this scheme is that it is immediately clear from the
definition of f what variables it depends on, and will get serialized along
with f (it's good to be conscious of this for reasons of performance and
security). The downside is that if the function body is refactored, the
list of captured upvars needs to be kept in-sync (a good IDE can obviously
help here).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list