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

Context-Aware AST Code Generator

Build a utility that generates JavaScript code from Abstract Syntax Trees (AST) while correctly handling context-specific constraints.

Problem

When generating JavaScript code from an AST, the same expression can require different handling depending on its syntactic context. Your task is to build a code generator that:

  1. Tracks syntactic context using flags (similar to how escodegen tracks context internally)
  2. Generates correct JavaScript code that respects context constraints
  3. Properly handles the in operator in different contexts (allowed in regular expressions but not in for-loop initializers)
  4. Correctly wraps expressions that need parenthesization based on their context

Requirements

Core Functionality

The generator should:

  1. Generate code from AST nodes using escodegen's code generation capabilities
  2. Handle context flags that control how expressions are generated:
    • Whether the in operator is allowed in the current position
    • Whether we're in a function body (affects directive handling)
  3. Apply correct transformations such as adding parentheses when expressions appear in positions that require them
  4. Support different generation modes for different contexts (e.g., expression vs statement context)

Test Cases

  • Generates a for-loop with expression in test position containing in operator correctly @test
  • Detects when a for-loop initializer would incorrectly contain in operator @test
  • Generates function with 'use strict' directive at the correct position @test

Implementation

@generates

API

/**
 * Generates JavaScript code from an AST node with context tracking.
 *
 * @param {Object} node - The AST node to generate code from
 * @param {Object} flags - Context flags that control generation
 * @param {boolean} flags.allowIn - Whether 'in' operator is allowed (false for for-loop init)
 * @param {boolean} flags.inFunctionBody - Whether we're inside a function body
 * @returns {string} Generated JavaScript code
 */
function generateWithFlags(node, flags) {
  // IMPLEMENTATION HERE
}

/**
 * Checks if an AST node contains an 'in' operator that would be invalid in the current context.
 *
 * @param {Object} node - The AST node to check
 * @returns {boolean} True if node contains 'in' operator
 */
function containsInOperator(node) {
  // IMPLEMENTATION HERE
}

module.exports = {
  generateWithFlags,
  containsInOperator
};

Dependencies { .dependencies }

escodegen { .dependency }

Provides JavaScript code generation from AST with context-aware features.

Install with Tessl CLI

npx tessl i tessl/npm-escodegen

tile.json