From 024b144aa5d73952bdded00cfde78867826eefd3 Mon Sep 17 00:00:00 2001 From: Bob Varioa Date: Wed, 31 Jul 2024 08:34:07 -0500 Subject: [PATCH] repl: add _ --- compiler/codegen.js | 46 +++++++++++++++++++++++++++++++++++++++++++++ runner/repl.js | 3 ++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/compiler/codegen.js b/compiler/codegen.js index 85fe8c52..c92d52e3 100644 --- a/compiler/codegen.js +++ b/compiler/codegen.js @@ -6340,6 +6340,52 @@ export default program => { program.id = { name: 'main' }; + if (Prefs.repl) { + let newBody = [{ + type: 'VariableDeclaration', + declarations: [ + { + type: 'VariableDeclarator', + id: { type: 'Identifier', name: '_' }, + init: { type: 'Identifier', name: 'undefined' } + } + ], + kind: 'let' + }]; + for (const node of program.body) { + if ( + // skip setting _ for: + // ; + node.type === 'EmptyStatement' + // print(...) + || node.type === 'ExpressionStatement' && node.expression.type === 'CallExpression' && node.expression.callee.name === 'print' + ) { + newBody.push(node); + } else if (node.type === 'ExpressionStatement') { + newBody.push({ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + left: { type: 'Identifier', name: '_' }, + operator: '=', + right: node.expression + } + }) + } else { + newBody.push(node, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + left: { type: 'Identifier', name: '_' }, + operator: '=', + right: { type: 'Identifier', name: 'undefined' } + } + }) + } + } + program.body = newBody; + } + program.body = { type: 'BlockStatement', body: program.body diff --git a/runner/repl.js b/runner/repl.js index f7ff2de6..d4919f42 100644 --- a/runner/repl.js +++ b/runner/repl.js @@ -3,7 +3,8 @@ import compile from '../compiler/wrap.js'; import util from 'node:util'; -process.argv.push('--no-opt-unused'); +process.argv.push('--no-opt-unused', '--repl'); +globalThis.argvChanged(); let repl; try {