Three Compiler Defects in a Mini Template Engine: Debug and Test
StringsModel answerLast updated
Diagnose three failures in a small Python template-to-source compiler: a lost ternary branch, a directory returned as a template, and a comment-only loop body, then fix each and add a regression test.
Loom is a compact template engine in the style of Jinja or Mako. It reads .loom files made of plain text, ${expr} substitutions and % if / % for control lines. It then translates each template into Python source, which is executed later to produce the output.
Three defects have been introduced into Loom's compiler. Each one is described below as a self-contained piece of the pipeline. For each, find the root cause, make the smallest correct fix, and write a regression test.
Part 1: A ternary default loses its alternative
A macro can declare a default argument using any Python expression, including a conditional expression:
<%def name="greet(user, title=('Mx' if user.get('formal') else 'Hey'))">
To emit a real Python def, the compiler converts the parsed default expression back into text with its own small printer (written before ast.unparse was available). Symptom: whatever user.get('formal') returns at render time, title is always 'Mx'.
Part 2: A directory is returned in place of a template file
Loom finds a template by walking an ordered list of search directories and returning the first matching path. Symptom: if an earlier directory contains a sub-directory whose name equals the requested template name, Loom returns that directory and stops. It never reaches the real file in a later directory, and rendering then fails when it tries to read a directory.
Part 3: A loop containing only comments will not compile
A % for block with at least one body line, where every body line is a ## comment, should compile to a loop that does nothing. Symptom: compiling it raises IndentationError.
Deliverables
For each part give:
- The root cause in one or two sentences.
- A minimal fix.
- A test that fails before the fix and passes after it.
Hints
Hint 1
For Part 1, look at how the printer handles the AST node for a conditional expression. That node has three children (`test`, `body`, `orelse`). Check how many of them the printer actually uses.
Hint 2
For Part 2, ask what the existence check in the lookup loop really tests. Does it distinguish files from directories? Your test needs a directory in the first search location and a real file in the second.
Hint 3
For Part 3, remember that Python requires at least one statement after a block header. Think about what the generator produces once comment lines are removed, and which no-op statement could fill the gap.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overall approach
The three failures sit in different stages of the pipeline: expression printing, template lookup and block code generation. They can be handled independently. For each one I would do the same thing:
- Write the smallest test that reproduces the symptom.
- Watch it fail for the reason described in the report. This confirms the test targets the bug and not just the feature in general.
- Apply the minimal fix.
- Watch the test pass.
Part 1: Ternary printed without its condition
Root cause. The printer's branch for ast.IfExp returns only the printed body. The test and orelse children are never emitted. Every conditional default therefore collapses to its "true" value, which is why title is always 'Mx'.
Fix. Emit all three parts, in Python's surface order (body if test else orelse), and wrap the result in parentheses so it keeps its meaning when nested in a larger expression or a default list.
if isinstance(node, ast.IfExp):
return (f"({unparse_expr(node.body)} if "
f"{unparse_expr(node.test)} else "
f"{unparse_expr(node.orelse)})")
Test. Parse "Mx" if is_formal else "Hey" with ast.parse(..., mode="eval").body, print it, then eval the text twice, once with is_formal=True and once with False. Assert "Mx" and "Hey" respectively. Before the fix both calls give "Mx".
Trade-offs and pitfalls.
- Always parenthesizing is slightly noisy but safe. Getting minimal parentheses right requires tracking operator precedence, and that is where printers usually go wrong.
- Test with a nested ternary too (
a if x else (b if y else c)) to catch precedence errors. - Long term, replacing the custom printer with
ast.unparseremoves this whole class of bug. That is a larger change than the task asks for, so mention it but do not do it here.
Part 2: A directory counts as a match
Root cause. The lookup uses os.path.exists, which returns True for any filesystem entry, including directories. An earlier directory holding a sub-directory with the template's name therefore wins, and the loop returns before it reaches the real file.
Fix. Check specifically for a regular file:
if os.path.isfile(candidate):
return candidate
Test. Create two temporary directories, early and late. In early, make a directory called footer.loom. In late, write a real file with the same name. Resolve footer.loom against [early, late] and assert that the result is the file in late and that os.path.isfile(result) is true. Before the fix, the result is the directory in early.
Trade-offs and pitfalls.
isfilefollows symlinks, so a symlink to a file still resolves. That is normally what you want.- A missing template should still produce a clear "not found" result (here
None) after all directories have been tried. Add a test for that case. - Do not fix this by catching the read error at render time. That hides the real problem and gives a worse error message.
Part 3: Empty block body after comment stripping
Root cause. The generator filters out ## comment lines when it builds a block's body, but it never checks whether anything is left. If every line was a comment, the output is a for ...: header with no indented statement. That is invalid Python, and compile() raises IndentationError.
Fix. If the filtered body is empty, substitute pass:
def compile_block(header, body_lines):
content = [ln for ln in body_lines if not ln.strip().startswith("##")]
if not content:
content = ["pass"]
return header + "\n" + "\n".join(" " + ln for ln in content)
Test. Call compile_block("for row in rows:", ["## TODO: later"]), then compile(src, "<loom>", "exec"). Before the fix this raises IndentationError. After it, the code compiles. Also exec it with rows = [1, 2, 3] and check that it runs without error and produces nothing.
Trade-offs and pitfalls.
- Putting the fix in the shared block generator covers
if,elseandforheaders in one place. passis the idiomatic placeholder. Emitting...would also work, butpassstates the intent more clearly.- Check that a body with real content is unchanged. A test with one comment and one real line should still produce just the real line.
Everything together
import ast, os, tempfile
def unparse_expr(node):
if isinstance(node, ast.IfExp):
return (f"({unparse_expr(node.body)} if "
f"{unparse_expr(node.test)} else "
f"{unparse_expr(node.orelse)})")
if isinstance(node, ast.Constant):
return repr(node.value)
if isinstance(node, ast.Name):
return node.id
raise TypeError(f"unsupported node: {ast.dump(node)}")
def resolve_template_path(name, search_dirs):
for d in search_dirs:
candidate = os.path.join(d, name)
if os.path.isfile(candidate):
return candidate
return None
def compile_block(header, body_lines):
content = [ln for ln in body_lines if not ln.strip().startswith("##")]
if not content:
content = ["pass"]
return header + "\n" + "\n".join(" " + ln for ln in content)
if __name__ == "__main__":
tree = ast.parse('"Mx" if is_formal else "Hey"', mode="eval").body
src = unparse_expr(tree)
assert eval(src, {"is_formal": True}) == "Mx"
assert eval(src, {"is_formal": False}) == "Hey"
with tempfile.TemporaryDirectory() as root:
early = os.path.join(root, "early")
late = os.path.join(root, "late")
os.makedirs(os.path.join(early, "footer.loom"))
os.makedirs(late)
real = os.path.join(late, "footer.loom")
with open(real, "w") as f:
f.write("ok")
assert resolve_template_path("footer.loom", [early, late]) == real
compile(compile_block("for row in rows:", ["## TODO: later"]), "<loom>", "exec")
print("all three regressions covered")
Complexity
Each fix adds constant work to a routine that is already linear in the size of its input: the expression tree, the number of search directories, or the number of body lines. Overall compile cost does not change.
Common mistakes
- Fixing first and testing afterwards, so the test never demonstrably failed.
- Printing the ternary in the wrong order (
test if body else orelse). - Patching the symptom (catching a read error, or swallowing
IndentationError) instead of the cause. - Testing only the broken case and not the neighbouring normal one (a real file in the first directory, a body with real statements, a non-ternary default).