Mojo Debugging
Your program runs, but the answer is wrong. Or it crashes, and you don’t know why. Debugging is the work of finding out what really happens inside, step by step. This lesson starts with the simplest tool (a well-placed print) and works up to a real debugger. You’ll use the simple ones far more often than you’d think.
Print debugging
Section titled “Print debugging”Here’s a program with a bug. The average of 90, 85 and 72 should be about 82.33:
def average(nums: List[Int]) -> Float64: var total = 0 for n in nums: total += n return Float64(total / len(nums))
def main(): var scores: List[Int] = [90, 85, 72] print("average:", average(scores))Output:
average: 82.0Where did the .33 go? The quickest way to find out is to print the values along the way. Send debug prints to standard error (file=stderr), so they don’t mix with your program’s real output:
from std.sys import stderr
def average(nums: List[Int]) -> Float64: var total = 0 for n in nums: total += n print("debug: total =", total, "count =", len(nums), "total / count =", total / len(nums), file=stderr) return Float64(total / len(nums))
def main(): var scores: List[Int] = [90, 85, 72] print("average:", average(scores))You’ll see:
debug: total = 247 count = 3 total / count = 82average: 82.0There it is: total / count is 82, not 82.33. In Mojo, / between two Int values gives an Int (see Mojo Operators), and turning 82 into a float afterwards can’t bring the decimals back. The fix is to convert before dividing: Float64(total) / Float64(len(nums)) gives 82.33333333333333.
A debug switch you can turn on
Section titled “A debug switch you can turn on”Instead of adding and deleting prints, you can keep them in the code behind a switch that’s off by default:
from std.sys import is_defined, stderr
def total(prices: List[Int]) -> Int: var sum = 0 for p in prices: comptime if is_defined["TRACE"](): print(" adding", p, "sum so far", sum, file=stderr) sum += p return sum
def main(): var prices: List[Int] = [3, 5, 9] print("total:", total(prices))Output:
total: 17Now turn the switch on with -D TRACE:
mojo run -D TRACE trace.mojo adding 3 sum so far 0 adding 5 sum so far 3 adding 9 sum so far 8total: 17comptime if decides at compile time. Without -D TRACE, the print isn’t just skipped, it isn’t in the program at all, so it costs nothing. Mojo Feature Toggles explains -D and is_defined in detail.
Turn on every check
Section titled “Turn on every check”Many bugs show up earlier, and with a clearer message, when all of Mojo’s asserts are on. While you’re hunting a bug, run with:
mojo run -D ASSERT=all app.mojoThat switches on every debug_assert and assert, in your code and in the standard library. See Mojo Debug Asserts for how they work.
Where did it crash?
Section titled “Where did it crash?”When a program crashes on a failed check, the first line already tells you where:
def last_item(xs: List[Int]) -> Int: return xs[len(xs)]
def main(): var xs: List[Int] = [4, 8, 15] print(last_item(xs))You’ll see:
At: crash.mojo:2:14: Assert Error: index 3 is out of bounds, valid range is 0 to 2...mojo: error: execution crashedLine 2, column 14: xs[len(xs)]. A list of 3 items has indexes 0 to 2, so the last one is xs[len(xs) - 1].
For a raised error that nobody catches, you only get the message by default. To see which functions it passed through, build with debug info and run with MODULAR_DEBUG=stack-trace-on-error:
mojo build -g app.mojoMODULAR_DEBUG=stack-trace-on-error ./appThe Mojo Errors lesson shows what that trace looks like and how to read it.
Using a debugger
Section titled “Using a debugger”A debugger lets you pause a running program at a line you choose (a breakpoint), look at every variable, and then go on one line at a time. Mojo comes with one: the mojo package includes the LLDB debugger with Mojo support, started with mojo debug.
You can point mojo debug at a .mojo file, and it builds the program with debug info for you. Or build it yourself first, with -O0 -g (no optimization, full debug info), which is what the docs recommend for the best results. Let’s debug this file, prices.mojo:
def total(prices: List[Int]) -> Int: var sum = 0 for p in prices: sum += p return sum
def main(): var prices: List[Int] = [3, 5, 9] var t = total(prices) print("total:", t)Output:
total: 17Build it and start the debugger:
mojo build -O0 -g prices.mojomojo debug ./pricesYou get an (lldb) prompt where you type commands. Here’s a session we ran, a little trimmed (the # notes are ours):
(lldb) b prices.mojo:4 # stop every time line 4 runsBreakpoint 1: where = prices`prices::total(...) + 200 at prices.mojo:4:13(lldb) run # start the program* thread #1, name = 'prices', stop reason = breakpoint 1.1 frame #0: prices`prices::total(prices=(size 3)[3, 5, 9]) at prices.mojo:4:13 3 for p in prices:-> 4 sum += p 5 return sum(lldb) p sum # print a variable(__mlir_type.`!kgen.scalar<index>`) 0(lldb) p p(__mlir_type.`!kgen.scalar<index>`) 3(lldb) continue # run to the next breakpoint(lldb) p sum(__mlir_type.`!kgen.scalar<index>`) 3(lldb) bt # how did we get here? * frame #0: prices`prices::total(prices=(size 3)[3, 5, 9]) at prices.mojo:4:13 frame #1: prices`prices::main() at prices.mojo:9:18(lldb) quitThe type names in brackets look strange (Int shows up as an internal type), but the values are right: after the first pass through the loop, sum went from 0 to 3. The commands you’ll use most:
| Command | What it does |
|---|---|
b file.mojo:4 |
Set a breakpoint on line 4 |
run |
Start the program |
p name |
Print a variable (frame variable prints all of them) |
next |
Run the current line, without going into functions it calls |
step |
Run the current line, going into a function it calls |
finish |
Run until the current function returns |
continue |
Run until the next breakpoint |
bt |
Show the call stack: which function called which |
quit |
Stop debugging |
Debugging in VS Code
Section titled “Debugging in VS Code”If you’d rather click than type, the Mojo extension for VS Code uses the same debugger behind a normal VS Code debugging screen. We haven’t run it for this page, so here’s what the official debugging guide describes:
- Open a Mojo file with a
mainand choose Debug Mojo File from the Run or Debug button in the editor toolbar (or press F5). - Click in the left margin to set breakpoints. Local variables show up inline and in the Variables panel, and the Call Stack panel shows how you got there.
- Turn on the Mojo Raise breakpoint to stop whenever a
raisestatement runs. mojo debug --vscode app.mojostarts a session in an open VS Code window from the terminal.
The guide also lists current limits: breakpoints with a condition expression aren’t supported (hit counts are), and the return value isn’t shown when you step out of a function.
breakpoint() in code
Section titled “breakpoint() in code”You can also put a breakpoint in the code itself, with the built-in breakpoint(). Under a debugger, the program pauses there. Without a debugger, it crashes:
def main(): print("before") breakpoint() print("after")You’ll see:
beforemojo: error: execution crashedSo don’t leave a bare breakpoint() in your code. A safer pattern is to put it behind a switch, so it’s only there when you ask for it:
from std.sys import is_defined
def main(): var count = 3 comptime if is_defined["DEBUG_ME"](): breakpoint() print("count:", count)Output:
count: 3mojo debug -D DEBUG_ME app.mojo then stops at that line, while a normal mojo run never sees the breakpoint().
Practice
Section titled “Practice”1. Find the off-by-one
Section titled “1. Find the off-by-one”This function should add up the numbers from 1 to n, so sum_to(4) should be 10. It prints 6. Add a debug print to stderr inside the loop to see which numbers it adds, then fix it.
def sum_to(n: Int) -> Int: var total = 0 for i in range(1, n): total += i return total
def main(): print(sum_to(4))Hint: print i each time round the loop. Which number is missing?
Show solution
def sum_to(n: Int) -> Int: var total = 0 for i in range(1, n + 1): total += i return total
def main(): print(sum_to(4))Output:
10The debug print shows 1, 2, 3 and no 4: range(1, n) stops before n. range(1, n + 1) includes it.
2. A trace switch
Section titled “2. A trace switch”Take the fixed sum_to and add a -D TRACE switch that prints adding <i> to stderr for each number, only when the switch is on. Without it, the program prints only 10.
Hint: from std.sys import is_defined, stderr and comptime if is_defined["TRACE"]():.
Show solution
from std.sys import is_defined, stderr
def sum_to(n: Int) -> Int: var total = 0 for i in range(1, n + 1): comptime if is_defined["TRACE"](): print("adding", i, file=stderr) total += i return total
def main(): print(sum_to(4))Output:
10With mojo run -D TRACE sum.mojo you also see adding 1 to adding 4 before the 10.
- Start with print debugging: print labels and values, to
stderr, one guess at a time. - Keep debug output behind a
comptime if is_defined["TRACE"]()switch and turn it on with-D TRACE. - Run with
-D ASSERT=allwhile hunting bugs so every check is on. - A failed check prints file:line first; for raised errors, use
mojo build -gplusMODULAR_DEBUG=stack-trace-on-error. mojo debugstarts LLDB:b,run,p,next,step,continue,bt. Build with-O0 -gfirst for the best results.- VS Code’s Mojo extension wraps the same debugger; a bare
breakpoint()crashes without a debugger.
Next up: feature toggles, the -D switches and compile-time checks in more detail.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Debugging (Mojo docs): the official guide to debugging in VS Code and from the command line.
mojo debugreference: every option, including attaching to a running program.breakpoint(): the built-in programmatic breakpoint.- LLDB tutorial: how the LLDB command line works, beyond the basics shown here.