Evaluate JavaScript AST directly

Viewed 558

I maintain doctest. The library uses an ECMAScript parser (Esprima) to extract comments from a JavaScript source file, then identifies “doctests” within these comments. For example:

'use strict';

//  identity :: a -> a
//
//  > identity (42)
//  42
const identity = x => x;

The AST is then discarded, and JavaScript code is spliced into the original source text in place of the doctests. Imagine something like the following:

'use strict';

//  identity :: a -> a
//
__doctest.enqueue (() => {
  assert.strictEqual (identity (42), 42);
});
const identity = x => x;

The modified source text is then saved to the file system. Finally, the newly created file is imported via require.

This approach works, but is circuitous:

SourceFile -> SourceText -> AST -> SourceText -> SourceFile -> SourceText -> AST -> Result
=(foo.js)=    (original) --------> (modified)    =(tmp.js)=    ====(require)====

Instead, I would like to do this:

SourceFile -> SourceText -> AST -> AST -> Result

I know how to perform the AST -> AST transformation. What I don't know is how to evaluate the modified AST. Surely it is not necessary to convert the AST to JavaScript source text only to have Node.js read the source text and recreate the AST!

0 Answers
Related