19. Building a REPL
Interactive programming, one line at a time
Open a terminal and type node or python. You get a prompt. Type an expression,
hit enter, see the result. Type another. This is a REPL — Read, Eval, Print,
Loop — and it's one of the most powerful tools for learning, debugging, and
exploratory programming.
REPLs feel like magic, but the core idea is almost absurdly simple: read a line, parse it, evaluate it, print the result, and do it again. The interesting parts are the edge cases — multi-line input, persistent state, pretty errors, and quality-of-life features that make the experience smooth.
The basic loop
REPL stands for four steps, and the simplest version is literally four lines:
function repl(env) {
while (true) {
const input = readLine("> "); // Read
const ast = parse(input); // Eval (parse + evaluate)
const result = evaluate(ast, env); // ...
print(result); // Print
} // Loop (the while)
}
That's the skeleton. Every REPL — from Python's interactive mode to Chrome DevTools to the Lisp machines of the 1960s — is a variation on this theme. The differences are all in how each step handles the messy real world.
Maintaining state
A useful REPL remembers what you've done. If you define a variable on line one, you should be able to use it on line ten. This means the environment lives outside the loop:
function repl() {
const env = new Environment(); // persists across iterations
while (true) {
const input = readLine("> ");
try {
const ast = parse(input);
const result = evaluate(ast, env); // same env every time
if (result !== undefined) print(result);
} catch (e) {
printError(e);
}
}
}
Each iteration reads, parses, and evaluates in the same environment. Variables accumulate. Functions stay defined. The REPL becomes a living workspace.
Expression vs. statement mode
Here's a subtle UX question: what should the REPL print?
> 2 + 3
5
> let x = 10
undefined // <-- is this helpful?
Most REPLs use a simple rule: if the input is an expression, print its value. If it's a statement (a declaration, assignment, or control flow), don't print anything — or print a quiet acknowledgment.
How do you tell the difference? One approach: try parsing as an expression first. If that succeeds, evaluate it and print the result. If it fails, parse as a statement and suppress the output:
function replEval(input, env) {
try {
const expr = parseExpression(input);
return { value: evaluate(expr, env), show: true };
} catch {
const stmt = parseStatement(input);
execute(stmt, env);
return { value: undefined, show: false };
}
}
Node.js does something similar — type 1 + 2 and you see 3. Type
const x = 5; and you see undefined (because declarations produce no value).
Handling multi-line input
Real code doesn't fit on one line. What happens when you type an incomplete expression?
> function add(a, b) {
... return a + b;
... }
The REPL needs to detect that the input is incomplete rather than invalid. The trick: catch the parse error and check whether it's an "unexpected end of input" error. If so, prompt for more. If it's a genuine syntax error, report it immediately.
function readMultiLine() {
let buffer = readLine("> ");
while (true) {
try {
parse(buffer);
return buffer; // parsed successfully — done
} catch (e) {
if (isIncomplete(e)) {
buffer += "\n" + readLine("... "); // ask for more
} else {
throw e; // real syntax error
}
}
}
}
The isIncomplete function typically checks for specific error messages like
"unexpected end of input" or looks at whether all brackets/braces/parens are
balanced. A simple heuristic: count open and close delimiters. If opens exceed
closes, the input is probably incomplete.
function isIncomplete(error) {
if (error.message.includes("Unexpected end")) return true;
return false;
}
function bracketsBalanced(input) {
let depth = 0;
for (const ch of input) {
if (ch === "(" || ch === "{" || ch === "[") depth++;
if (ch === ")" || ch === "}" || ch === "]") depth--;
}
return depth <= 0;
}
Special commands
REPLs typically support meta-commands that don't go through the parser. These
start with a prefix (: or . or /) so they can't collide with valid code:
const commands = {
":help": () => print("Commands: :help, :env, :clear, :quit"),
":env": (env) => print(env.dump()),
":clear": (env) => env.clear(),
":quit": () => process.exit(0),
};
function handleInput(input, env) {
const cmd = commands[input.trim()];
if (cmd) return cmd(env);
// otherwise, parse and evaluate normally
}
:env is particularly useful — it dumps every variable currently defined, so you
can see your workspace at a glance. :clear resets the environment when you want
a fresh start without restarting the REPL.
History
Typing the same expression twice is tedious. Every good REPL keeps a history buffer:
class History {
constructor() {
this.entries = [];
this.cursor = 0;
}
push(line) {
this.entries.push(line);
this.cursor = this.entries.length;
}
up() {
if (this.cursor > 0) this.cursor--;
return this.entries[this.cursor] || "";
}
down() {
if (this.cursor < this.entries.length) this.cursor++;
return this.entries[this.cursor] || "";
}
}
The cursor starts at the end. Pressing up moves backward through history; pressing down moves forward. When you submit a new line, it's appended and the cursor resets to the end.
In Node.js, the built-in readline module provides this for free. In a
browser-based REPL, you wire up keydown listeners for the up and down arrows.
Pretty-printing results
Raw console.log output isn't great for complex values. A good REPL formats
results with care:
function prettyPrint(value) {
if (value === null) return "null";
if (value === undefined) return "undefined";
if (typeof value === "string") return `"${value}"`;
if (Array.isArray(value)) {
if (value.length > 10) {
const shown = value.slice(0, 10).map(prettyPrint).join(", ");
return `[${shown}, ... (${value.length} items)]`;
}
return `[${value.map(prettyPrint).join(", ")}]`;
}
if (typeof value === "object") {
const keys = Object.keys(value);
const pairs = keys.slice(0, 5).map(k => `${k}: ${prettyPrint(value[k])}`);
const suffix = keys.length > 5 ? `, ... (${keys.length} keys)` : "";
return `{ ${pairs.join(", ")}${suffix} }`;
}
return String(value);
}
Long arrays get truncated with an item count. Objects show their first few keys.
Strings are quoted so you can distinguish "42" from 42. Functions might show
their name and parameter list instead of [Function].
Error display
The most important REPL rule: errors must never crash the loop. An error in one expression should not prevent you from typing the next one.
while (true) {
const input = readMultiLine();
try {
const result = replEval(input, env);
if (result.show) print(prettyPrint(result.value));
} catch (e) {
printError(e); // show it, but keep going
}
}
Good error display shows the error type, message, and — if available — the position in the input where things went wrong:
> 1 + * 3
SyntaxError: Unexpected token '*' at column 5
> let x = ;
SyntaxError: Expected expression after '=' at column 9
> y + 1
ReferenceError: Undefined variable 'y'
The REPL keeps running after each error. Your environment is untouched. You can fix your typo and try again.
Tab completion
When the user presses Tab, the REPL can suggest completions based on what's currently in scope:
function complete(partial, env) {
const names = env.allNames(); // all defined variables
return names.filter(n => n.startsWith(partial));
}
If there's exactly one match, fill it in. If there are multiple, show them all and let the user keep typing. In a browser-based REPL, you can render these as a dropdown.
A complete REPL
Putting it all together, here's a complete REPL in about 50 lines. It assumes
you have parse, evaluate, and Environment from earlier articles:
function repl() {
const env = new Environment();
const history = new History();
const commands = {
":help": () => "Commands: :help :env :clear :quit",
":env": () => env.dump(),
":clear": () => { env.clear(); return "Environment cleared."; },
":quit": () => { process.exit(0); },
};
while (true) {
let input = readLine("> ");
// Special commands
const cmd = commands[input.trim()];
if (cmd) { print(cmd()); continue; }
// Multi-line accumulation
while (!bracketsBalanced(input)) {
input += "\n" + readLine("... ");
}
history.push(input);
try {
// Try as expression first
try {
const expr = parseExpression(input);
const value = evaluate(expr, env);
print(prettyPrint(value));
} catch (parseErr) {
// Fall back to statement
const stmt = parse(input);
execute(stmt, env);
}
} catch (e) {
printError(e.message);
}
}
}
The flow: check for special commands, accumulate multi-line input, try expression mode (print the value), fall back to statement mode (no output), and catch all errors without crashing.
Why REPLs matter
REPLs aren't just a convenience. They change how you think about programming. Instead of write-compile-run-debug cycles, you get immediate feedback. You can test a function as soon as you write it. You can inspect live state. You can build a program incrementally, one expression at a time.
This is why Lisp programmers have always loved the REPL — it's been central to Lisp culture since the 1960s. And it's why every modern language ships with one.
Next, we'll look at what happens when things go wrong in compiled code: how source maps connect generated bytecode back to the original source, so error messages and debuggers can point to the right line.
Try It Yourself — REPL
Type expressions and statements into the REPL below. The environment persists
across lines — define a variable, then use it later. Try special commands like
:help, :env, and :clear.