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-2/

AST Code Generator

Build a JavaScript code generator that transforms Abstract Syntax Trees (ASTs) into formatted JavaScript source code.

Requirements

Implement a module that provides the following capabilities:

  1. Basic Code Generation: Convert AST nodes representing JavaScript expressions and statements into executable JavaScript code
  2. Formatting Options: Support both readable (formatted with indentation) and minified (compact) output modes
  3. Operator Handling: Correctly handle binary expressions with proper operator precedence and parenthesization

Implementation Details

Your implementation should:

  • Accept an AST node conforming to the Mozilla Parser API specification
  • Generate syntactically correct JavaScript code from the AST
  • Support a formatting option that allows switching between readable and compact output
  • Handle binary expressions (arithmetic and logical operators) correctly
  • Return the generated code as a string

Input

  • An AST node object with standard Mozilla Parser API properties (e.g., type, operator, left, right, value, etc.)
  • Optional configuration for output formatting

Output

  • A string containing the generated JavaScript code

Test Cases { .test }

Test 1: Simple Binary Expression @test

// test/generator.test.js
const ast = {
  type: 'BinaryExpression',
  operator: '+',
  left: { type: 'Literal', value: 5 },
  right: { type: 'Literal', value: 10 }
};

const result = generateCode(ast);
// Expected: '5 + 10'

Test 2: Nested Expression @test

// test/generator.test.js
const ast = {
  type: 'BinaryExpression',
  operator: '*',
  left: {
    type: 'BinaryExpression',
    operator: '+',
    left: { type: 'Literal', value: 2 },
    right: { type: 'Literal', value: 3 }
  },
  right: { type: 'Literal', value: 4 }
};

const result = generateCode(ast);
// Expected: '(2 + 3) * 4'

Test 3: Formatted vs Compact Output @test

// test/generator.test.js
const ast = {
  type: 'Program',
  body: [{
    type: 'ExpressionStatement',
    expression: {
      type: 'BinaryExpression',
      operator: '+',
      left: { type: 'Literal', value: 1 },
      right: { type: 'Literal', value: 2 }
    }
  }]
};

const formatted = generateCode(ast, { format: 'readable' });
const minified = generateCode(ast, { format: 'compact' });
// Formatted should include whitespace and indentation
// Minified should be compact: '1+2;'

Dependencies { .dependencies }

escodegen { .dependency }

JavaScript code generator from AST.

Install with Tessl CLI

npx tessl i tessl/npm-escodegen

tile.json