The question title speaks for itself. I'm specifically thinking in terms of a Node.js server. Additionally, this question is assuming that you don't need eval()
.
Also, if this is not possible, why not?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityThe question title speaks for itself. I'm specifically thinking in terms of a Node.js server. Additionally, this question is assuming that you don't need eval()
.
Also, if this is not possible, why not?
It's easy to compile any language, no matter how dynamic, to machine code. It just won't be efficient machine code, since it will usually do a lot of dispatching based on run time type tags and looking up values in hash tables, much like a (bytecode) interpreter.
In the simplest case, just compile C code like
#include <some_js_vm.h>
static char[] source = "... JavaScript ...";
int main() {
js_run(source);
return 0;
}
For JavaScript without eval
, there are still several features that require such inefficient machine code when compiled statically:
with
, which modifies scope and semantics of variables based on an object's members. This is only a problem because of the next point.new Function(str)
and other moral equivalents to eval
.In fact, Javascript is (inside several major browsers) often "compiled" using Just-in-Time compilation techniques (read about the V8 Javascript engine). But as delnan explained, there are case where it is not worthwhile. AFAIK some implementations use Tracing JIT compilation techniques.
And eval
could be implemented by calling the compiler. Several Lisp implementations (notably SBCL) are doing that (and Lisp can be as dynamic as Javascript).
And asmjs.org defines a specification of a subset of Javascript which is designed to be easy to compile.
Node.js uses the V8 engine, which is a pure compiler. It never interprets. There isn't even an interpreter in V8, just two compilers.