CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-escodegen

ECMAScript code generator that transforms Mozilla's Parser API ASTs back into executable JavaScript code

95

1.07x
Overview
Eval results
Files

task.mdevals/scenario-4/

AST Code Formatter

A JavaScript utility that transforms Abstract Syntax Trees (AST) into formatted JavaScript code while preserving comments with proper indentation and spacing.

Capabilities

Transforms AST to formatted code

  • Accepts an AST object and returns formatted JavaScript code with preserved comments @test
  • Preserves multiline block comments with proper indentation matching the surrounding code @test
  • Maintains blank lines from the original source code @test
  • Handles inline trailing comments with appropriate spacing @test

Implementation

@generates

The formatter should accept an AST object that includes:

  • A body array containing statement nodes
  • A comments array containing comment objects
  • A tokens array containing token objects
  • A sourceCode string containing the original source

The output should be formatted JavaScript code with all comments preserved in their proper positions.

API

/**
 * 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 };

Test Cases

The test file should verify:

  1. A simple function with a multiline block comment is formatted with the comment indented to match the function body @test
  2. Code with blank lines between statements preserves those blank lines in the output @test
  3. Inline trailing comments maintain proper spacing from the code they follow @test

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 comment

Dependencies { .dependencies }

escodegen { .dependency }

Provides AST to JavaScript code generation with comment preservation support.

Install with Tessl CLI

npx tessl i tessl/npm-escodegen

tile.json