KatInterview

Three Compiler Defects in a Mini Template Engine: Debug and Test

StringsModel answer
MediumModel answerStringsdebuggingcode-generationast

Last 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:

  1. The root cause in one or two sentences.
  2. A minimal fix.
  3. 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.