Skip to content

Commit

Permalink
Dev: Improve readability of debug output for eval
Browse files Browse the repository at this point in the history
  • Loading branch information
overlookmotel committed Jan 4, 2023
1 parent ae5691f commit afde84c
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions lib/init/eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ function compile(code, tracker, filename, isIndirectEval, state, isStrict) {
}

// Return instrumented code
code = generate(ast, {retainLines: true, compact: true}).code;
code = generateCode(ast); // eslint-disable-line no-use-before-define

if (DEBUG) {
/* eslint-disable no-console */
Expand All @@ -260,11 +260,8 @@ function wrapInFunction(ast, internalPrefixNum) {
internalVarNode(TRACKER_VAR_NAME_BODY, internalPrefixNum),
internalVarNode(GET_SCOPE_ID_VAR_NAME_BODY, internalPrefixNum)
],
t.callExpression(
t.identifier('eval'), [
t.stringLiteral(generate(ast, {retainLines: true, compact: true}).code)
]
)
// eslint-disable-next-line no-use-before-define
t.callExpression(t.identifier('eval'), [generateCodeStringNode(ast)])
);
}

Expand All @@ -281,3 +278,28 @@ function wrapInFunctionCall(fnNode, externalPrefixNum) {
function internalVarNode(name, prefixNum) {
return t.identifier(`${INTERNAL_VAR_NAMES_PREFIX}${prefixNum || ''}_${name}`);
}

/**
* Generate code from AST.
* If debugging enabled, generates in a more readable form.
* @param {Object} ast - AST
* @returns {string} - Generated code
*/
const generateCode = DEBUG
? ast => generate(ast).code
: ast => generate(ast, {retainLines: true, compact: true}).code;

/**
* Generate a string literal AST node for a string of code generated from AST.
* If debugging enabled, generates a template literal instead with line breaks retained
* for greater readability.
* @param {Object} ast - AST
* @returns {Object} - String literal / template literal AST node
*/
const generateCodeStringNode = DEBUG
? ast => t.templateLiteral([
t.templateElement({
raw: `\n${generateCode(ast).replace(/\\/g, '\\\\').replace(/`/g, '\\`')}\n`
}, true)
], [])
: ast => t.stringLiteral(generateCode(ast));

0 comments on commit afde84c

Please sign in to comment.