In the Add-on SDK we have a problem that is both annoying and confusing for a lot of our users. The problem is not SDK-specific though and maybe interesting for anyone dealing with JS in concurrent execution contexts.
We quickly discovered that not a lot of people are comfortable with message passing APIs, but even putting that aside it’s really annoying to be creating separate content script files for a few lines of code (most of the add-ons have content scripts that consist of few lines of code, unless accompanied with external js libraries like jQuery):
As an option we also allow passing content scripts in form of JS string, which is far from ideal:
What you would actully want is to just write a function that will be executed in the context of the content. Unfortunately it’s not just matter of serialising function and then evaluating it in the context, since functions can access bindings from the outer scopes.
If we could prove that function does not refers to anything but arguments passed to it or definitions with in it, it would be pretty safe to transplant it into completely different execution context:
As a matter of fact such
isolate function can be implemented relatively easy,
all it has to do is serialise given function, parse it, perform static analyzes
to verify no outer references are made and return some wrapping of source back.
If given function does have prohibited references then throw
With a great projects like Esprima, Acorn parsing JS is no-brainer. Also for SDK we could / should just use Spidermonkey parser API, but since all of them produce de facto standad AST format we can swap parsers as we pleased. So the only remaining chunk of work was static analysis. I made few micro-libraries solving very specific problems.
While playing with AST I quickly discovered the need for binary operations for logical sets. So I end up writing interset small library for doing exactly that:
ECMAScript scope analyzer. This Library provides set of functions that perform analyzes on the nodes of the AST in the de facto AST format. All the API function take AST nodes denoting a lexical scope and performed static analyzes at the given scope level (Note: examples use esprima but library does not really cares about it and expects AST format implemented by all popular JS parsers):
ECMAScript function isolation analyzer. This is very alpha, but intention is to provide API for performing static analyzes on the JS AST nodes denoting a function definition / declaration and perform analyzes to gather info about their isolation:
If this experiment works out in practice that would allow us to explore a lot more to make new and brave concurrent world a lot more accessible and pleasant to use for our users.
All the libraries mentioned are open source and work both in SDK and Node, probably in browsers too. So feel free to play with them, break them and maybe even contribute fixes!