ECMAScript code generator that transforms Mozilla's Parser API ASTs back into executable JavaScript code
95
A JavaScript utility that transforms Abstract Syntax Trees (AST) into formatted JavaScript code while preserving comments with proper indentation and spacing.
@generates
The formatter should accept an AST object that includes:
body array containing statement nodescomments array containing comment objectstokens array containing token objectssourceCode string containing the original sourceThe output should be formatted JavaScript code with all comments preserved in their proper positions.
/**
* Formats an AST into JavaScript code with preserved comments.
*
* @param {Object} ast - The AST object with comments and tokens attached
* @param {string} originalSource - The original source code string
* @returns {string} The formatted JavaScript code with preserved comments
*/
function formatWithComments(ast, originalSource) {
// IMPLEMENTATION HERE
}
module.exports = { formatWithComments };The test file should verify:
Example test case for multiline comment indentation:
const input = {
type: 'Program',
body: [
{
type: 'FunctionDeclaration',
id: { type: 'Identifier', name: 'example' },
params: [],
body: {
type: 'BlockStatement',
body: [
{
type: 'ReturnStatement',
argument: { type: 'Literal', value: 42 }
}
]
}
}
],
comments: [
{
type: 'Block',
value: '* This is a multiline\n * block comment',
range: [20, 60]
}
],
tokens: [],
sourceCode: 'function example() {\n /* This is a multiline\n * block comment */\n return 42;\n}'
};
const result = formatWithComments(input, input.sourceCode);
// Should contain the properly indented multiline commentProvides AST to JavaScript code generation with comment preservation support.
Install with Tessl CLI
npx tessl i tessl/npm-escodegendocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10