Compile a Mini Language to Three-Address Code
StringsModel answerLast updated
Parse a small line-based language of assignments and flat if-else blocks, then emit a deterministic three-address IR with temporaries and jump labels.
Background
Compilers translate source code through several layers before producing machine instructions. One common intermediate step is three-address code (also called operation triads): a flat sequence of simple instructions where each operation has at most two inputs and one output. Temporaries hold intermediate values; labels and jumps encode control flow.
Your task is to build a minimal compiler front end for a toy language and emit this kind of IR.
The Language
The language has two kinds of statement.
Assignments — one per line:
a = 1
x = b + c
If-else blocks — always braced, always paired:
if (condition) {
x = 10
} else {
x = 20
}
Expressions are built from integer literals and variable names using +, -, *, / with standard precedence. Parentheses are allowed.
Conditions compare two expressions with a single comparison operator (==, !=, <, >, <=, >=).
Hard constraints:
ifblocks cannot be nested.- Every
ifmust have a matchingelse. - Each brace-delimited block contains exactly one assignment.
Input
A list of strings — one line of source code per string. Brace placement is flexible; } else { may appear on its own line or combined.
[
"a = 1",
"if (a + b == 3) {",
" x = 10",
"} else {",
" x = 20",
"}"
]
Output
A flat list of triads. Each triad is a 4-tuple (op, arg1, arg2, result). Use "_" for unused slots.
Introduce temporaries t1, t2, … and labels L1, L2, … in left-to-right, innermost-first emission order. The same input must always produce the same output.
Expected output for the example above:
("=", "1", "_", "a" )
("+", "a", "b", "t1")
("==", "t1", "3", "t2")
("if_false", "t2", "L1", "_" )
("=", "10", "_", "x" )
("goto", "L2", "_", "_" )
("label", "L1", "_", "_" )
("=", "20", "_", "x" )
("label", "L2", "_", "_" )
Requirements
- Tokenize the input, handling keywords, identifiers, integers, operators, and punctuation.
- Parse using recursive descent; enforce all three hard constraints with descriptive errors.
- Emit triads in execution order during parsing (syntax-directed translation).
- State clearly how temporaries and labels are numbered.
- Handle edge cases: blank lines, parenthesized sub-expressions,
==vs=, keywords used as variable names.
Hints
Hint 1
Tokenize the entire program into a flat token list first, rather than processing line by line — it makes brace placement irrelevant and simplifies the parser significantly.
Hint 2
Each expression-parsing function should return the *name* that holds its result: either an atom (like "a" or "3") or a freshly allocated temporary. That way the caller can pass it directly as an argument to the next instruction.
Hint 3
Allocate both labels for an if-else up front, before emitting anything for that block. Emit `if_false … L_else`, then the then-branch, then `goto L_end`, then `label L_else`, then the else-branch, then `label L_end`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic compiler front end broken into three stages: tokenize, parse, emit. The key insight is syntax-directed translation: triads are emitted as a side effect of parsing, so emission order automatically matches execution order.
Stage 1 — Tokenize
A single regex pass over every line produces a flat list of (kind, value, lineno) tuples. The regex tries two-character operators (==, !=, <=, >=) before single-character ones, so == is never misread as two = tokens. Keywords (if, else) get their own kind so they can never be mistaken for identifiers.
Stage 2 — Parse (recursive descent)
The grammar maps directly to functions:
program → statement*
statement → if_stmt | assign
if_stmt → 'if' '(' condition ')' block 'else' block
block → '{' assign '}'
assign → ID '=' expr
condition → expr CMP expr
expr → term (('+' | '-') term)*
term → factor (('*' | '/') factor)*
factor → NUM | ID | '(' expr ')'
Precedence falls out of the layering: *// bind tighter because term is nested inside expr. Left-associativity comes from the while loops in expr and term.
Stage 3 — Emit triads
Each expression function returns the name holding its result — either an atom or a new tK. An arithmetic instruction stores into a fresh temporary; an assignment stores into the named variable; comparisons store into a temporary that the subsequent if_false consumes.
If-else lowering pattern:
<condition triads> → tc
(if_false, tc, L_else, _)
<then-branch>
(goto, L_end, _, _)
(label, L_else, _, _)
<else-branch>
(label, L_end, _, _)
Both labels are allocated before anything is emitted, so forward references are resolved.
Naming rules (deterministic):
- Temporaries: a single global counter incremented on each arithmetic or comparison instruction.
t1is the first result emitted, left-to-right. - Labels: a second global counter. Each
ifclaims two labels in order:L_else = L(2k-1),L_end = L(2k).
Complexity
- Time: O(N) — the tokenizer touches each character once; the parser consumes each token once with O(1) lookahead.
- Space: O(N) — token list plus output IR. Recursion depth is bounded by parenthesis nesting, not by the number of statements.
Common mistakes
- Emitting labels after back-patching rather than allocating them up front — this breaks forward jumps.
- Returning a fresh temporary for atoms like
"3"or"a"— unnecessary and inflates the IR. Only allocate a temporary when you actually compute something. - Processing line by line instead of tokenizing holistically — breaks when
} else {spans lines or when a condition spans a line boundary. - Forgetting to reject keywords as identifiers —
if = 1should raise an error immediately.
Full Solution
import re
from typing import List, Tuple
Triad = Tuple[str, str, str, str] # (op, arg1, arg2, result); '_' = unused
TOKEN_RE = re.compile(
r"\s*(?:(\d+)|([A-Za-z_]\w*)|(==|!=|<=|>=|[+\-*/=<>(){}]))"
)
KEYWORDS = {"if", "else"}
CMP_OPS = {"==", "!=", "<", ">", "<=", ">="}
def tokenize(lines: List[str]) -> list:
tokens = []
for lineno, line in enumerate(lines, 1):
pos = 0
while pos < len(line):
if not line[pos:].strip():
break
m = TOKEN_RE.match(line, pos)
if not m:
ch = line[pos:].strip()[0]
raise SyntaxError(f"line {lineno}: unexpected character {ch!r}")
num, ident, op = m.groups()
if num is not None:
tokens.append(("NUM", num, lineno))
elif ident is not None:
kind = "KW" if ident in KEYWORDS else "ID"
tokens.append((kind, ident, lineno))
else:
tokens.append(("OP", op, lineno))
pos = m.end()
return tokens
class TriadCompiler:
def __init__(self, lines: List[str]):
self.toks = tokenize(lines)
self.i = 0
self.code: List[Triad] = []
self.temp_count = 0
self.label_count = 0
# ── helpers ──────────────────────────────────────────────────────────────
def peek(self):
if self.i < len(self.toks):
return self.toks[self.i]
last_line = self.toks[-1][2] if self.toks else 0
return ("EOF", None, last_line)
def advance(self):
tok = self.peek()
if tok[0] == "EOF":
raise SyntaxError("unexpected end of input")
self.i += 1
return tok
def expect(self, value: str):
tok = self.advance()
if tok[1] != value:
raise SyntaxError(
f"line {tok[2]}: expected {value!r}, got {tok[1]!r}"
)
return tok
def new_temp(self) -> str:
self.temp_count += 1
return f"t{self.temp_count}"
def new_label(self) -> str:
self.label_count += 1
return f"L{self.label_count}"
def emit(self, op, a1="_", a2="_", res="_"):
self.code.append((op, a1, a2, res))
# ── grammar ──────────────────────────────────────────────────────────────
def compile(self) -> List[Triad]:
while self.peek()[0] != "EOF":
self.statement()
return self.code
def statement(self):
if self.peek()[1] == "if":
self.if_stmt()
else:
self.assign()
def if_stmt(self):
self.expect("if")
self.expect("(")
cond = self.condition()
self.expect(")")
# Allocate both labels before emitting anything
l_else = self.new_label()
l_end = self.new_label()
self.emit("if_false", cond, l_else)
self.block()
tok = self.peek()
if tok[1] != "else":
raise SyntaxError(f"line {tok[2]}: 'if' must have a matching 'else'")
self.advance()
self.emit("goto", l_end)
self.emit("label", l_else)
self.block()
self.emit("label", l_end)
def block(self):
self.expect("{")
tok = self.peek()
if tok[1] == "if":
raise SyntaxError(f"line {tok[2]}: nested 'if' is not allowed")
if tok[1] == "}":
raise SyntaxError(f"line {tok[2]}: block cannot be empty")
self.assign()
tok = self.peek()
# Another identifier here would mean a second statement
if tok[0] == "ID":
raise SyntaxError(
f"line {tok[2]}: only one statement allowed per block"
)
self.expect("}")
def assign(self):
tok = self.advance()
if tok[0] != "ID":
raise SyntaxError(
f"line {tok[2]}: expected variable name, got {tok[1]!r}"
)
target = tok[1]
self.expect("=")
value = self.expr()
self.emit("=", value, "_", target)
def condition(self):
left = self.expr()
tok = self.peek()
if tok[1] not in CMP_OPS:
raise SyntaxError(
f"line {tok[2]}: expected comparison operator, got {tok[1]!r}"
)
op = self.advance()[1]
right = self.expr()
res = self.new_temp()
self.emit(op, left, right, res)
return res
def expr(self) -> str:
left = self.term()
while self.peek()[1] in ("+", "-"):
op = self.advance()[1]
right = self.term()
res = self.new_temp()
self.emit(op, left, right, res)
left = res
return left
def term(self) -> str:
left = self.factor()
while self.peek()[1] in ("*", "/"):
op = self.advance()[1]
right = self.factor()
res = self.new_temp()
self.emit(op, left, right, res)
left = res
return left
def factor(self) -> str:
tok = self.peek()
if tok[0] == "NUM":
self.advance()
return tok[1]
if tok[0] == "ID":
self.advance()
return tok[1]
if tok[1] == "(":
self.advance()
val = self.expr()
self.expect(")")
return val
raise SyntaxError(
f"line {tok[2]}: expected expression, got {tok[1]!r}"
)
def parse_to_triads(lines: List[str]) -> List[Triad]:
"""
Compile a mini-language program to three-address IR.
Returns a list of (op, arg1, arg2, result) tuples.
Unused slots are filled with '_'.
"""
return TriadCompiler(lines).compile()
# ── tests ─────────────────────────────────────────────────────────────────────
def test_all():
# Simple assignment — no temporary needed for a plain atom
assert parse_to_triads(["a = 1"]) == [("=", "1", "_", "a")]
# Binary expression produces one temporary
assert parse_to_triads(["x = a + b"]) == [
("+", "a", "b", "t1"),
("=", "t1", "_", "x"),
]
# Full if-else example from the problem statement
result = parse_to_triads([
"a = 1",
"if (a + b == 3) {",
" x = 10",
"} else {",
" x = 20",
"}"
])
assert result == [
("=", "1", "_", "a"),
("+", "a", "b", "t1"),
("==", "t1", "3", "t2"),
("if_false", "t2", "L1", "_"),
("=", "10", "_", "x"),
("goto", "L2", "_", "_"),
("label", "L1", "_", "_"),
("=", "20", "_", "x"),
("label", "L2", "_", "_"),
]
# Precedence: (a+b)*c - d/e
result = parse_to_triads(["x = (a + b) * c - d / e"])
assert result == [
("+", "a", "b", "t1"),
("*", "t1", "c", "t2"),
("/", "d", "e", "t3"),
("-", "t2", "t3", "t4"),
("=", "t4", "_", "x"),
]
# Two if-else blocks → labels L1/L2 then L3/L4
result = parse_to_triads([
"if (a == 1) {", " x = 5", "} else {", " x = 6", "}",
"if (b == 2) {", " y = 7", "} else {", " y = 8", "}",
])
label_names = [t[1] for t in result if t[0] == "label"]
assert label_names == ["L1", "L2", "L3", "L4"]
# Constraint: nested if must raise
try:
parse_to_triads([
"if (a == 1) {",
" if (b == 2) {", " x = 3", " } else {", " x = 4", " }",
"} else {", " x = 5", "}"
])
assert False, "expected SyntaxError"
except SyntaxError as e:
assert "nested" in str(e).lower()
# Constraint: missing else must raise
try:
parse_to_triads(["if (a == 1) {", " x = 2", "}"])
assert False, "expected SyntaxError"
except SyntaxError as e:
assert "else" in str(e).lower()
# Constraint: empty block must raise
try:
parse_to_triads(["if (a == 1) {", "} else {", " x = 2", "}"])
assert False, "expected SyntaxError"
except SyntaxError as e:
assert "empty" in str(e).lower()
print("All tests passed.")
if __name__ == "__main__":
test_all()
Key design decisions
No temporary for atoms. When factor consumes a literal or identifier it returns the atom itself. Only instructions that compute something allocate a temporary. This keeps the IR lean and matches what real compilers do.
Determinism via counters. Temporaries and labels depend only on parse order, which is deterministic. The same source always produces identical IR, making the output easy to test and diff.
Constraint enforcement is local. block handles all three structural rules (no nesting, no empty blocks, exactly one statement) in one place, rather than scattering checks across the grammar. This makes it easy to extend or tighten the rules later.