Tools for finding a bug: assertions, a hand-kept call stack, tracing and timing.
import debug
The debug package holds a few small tools for when the program is not doing the right thing. Assert checks a condition that should always hold. Enter and Exit keep a call stack by hand, so an error message can say where in the program it happened. Trace prints what the program is doing, the timers show which part is slow, and MemStats counts allocations to find a leak.
It is meant for development. For messages a running service keeps, use log; for exact timing and allocation counters in your own code, runtime and mem; for benchmarks inside tests, testing.
The things people get wrong:
•
Assert is an ordinary function: it runs in release builds too, and its message is built even when the condition holds. Keep expensive work out of the message.
•
The stack, the trace switch and the timers are globals with no lock, shared by every thread. In a program with threads the stack mixes frames from all of them.
•
The stack is only as good as its Enter and Exit calls. Always pair them with defer debug.Exit().
•
MemStats only has numbers in a build with memory counting on; a normal run gets a line saying so.
Trace lines and failed assertions go to standard error, so they do not mix with the program's normal output.
Say where an error happened
An error message like empty price is hard to act on in a big program: which item, and who asked for it? Call Enter at the start of the functions you care about and defer debug.Exit() right after it, so the frame is removed on every return path. Stack then gives the path from the outermost frame to the current one, joined with >. The frame is just text, so it can carry the item being worked on.
error in load_catalogue > load_item cake > parse_price: empty price
2 items loaded, depth now 0
After the outer function returns, Depth is back at 0. If it is not, some function called Enter without a matching Exit, which is exactly the bug that defer prevents.
Trace the calls of a recursive function
EnableTrace(true) switches tracing on: from then on Enter and Exit print an enter and an exit line, and Trace prints its message after the current stack. With tracing off, Trace prints nothing, so trace calls can stay in the code and be switched on with a flag, for instance from a setting or a command line option.
debug-trace-calls.salam
import debug
importstrfuncfib(n: int): int:
debug.Enter("fib " + str.FromInt(n asi64))
defer debug.Exit()
if n < 2:
debug.Trace("base case")
ret n
endretfib(n - 1) + fib(n - 2)
endfuncmain:
debug.Trace("not printed, tracing is off")
debug.EnableTrace(true)
result := fib(3)
debug.EnableTrace(false)
debug.Trace("not printed either")
printerrln"fib(3) =", result
end
Output
[TRACE] fib 3: enter
[TRACE] fib 3 > fib 2: enter
[TRACE] fib 3 > fib 2 > fib 1: enter
[TRACE] fib 3 > fib 2 > fib 1: base case
[TRACE] fib 3 > fib 2 > fib 1: exit
[TRACE] fib 3 > fib 2 > fib 0: enter
[TRACE] fib 3 > fib 2 > fib 0: base case
[TRACE] fib 3 > fib 2 > fib 0: exit
[TRACE] fib 3 > fib 2: exit
[TRACE] fib 3 > fib 1: enter
[TRACE] fib 3 > fib 1: base case
[TRACE] fib 3 > fib 1: exit
[TRACE] fib 3: exit
fib(3) = 2
Reading the lines from top to bottom shows the order of the calls; the indentation you would draw by hand is the length of each stack. All of it goes to standard error, like the last line, which this example prints with printerrln.
Time parts of a program
StartTimer starts a named timer and StopTimer returns the milliseconds since it started, measured with the monotonic clock, so a change of the system time does not disturb it. Starting a timer that already exists restarts it. StopTimer does not remove the timer: calling it again later gives a larger number, which is handy for lap times. A name that was never started gives 0.
debug-timers.salam
import debug
funcbusy(n: int): int:
mut total := 0repeat n in i:
total = (total + i * i) % 1000003endret total
endfuncmain:
debug.StartTimer("all")
debug.StartTimer("step")
a := busy(200000)
first := debug.StopTimer("step")
debug.StartTimer("step")
b := busy(200000)
second := debug.StopTimer("step")
total := debug.StopTimer("all")
later := debug.StopTimer("all")
println a == b
println"both steps fit in the total:", first + second <= total
println"a timer keeps running after StopTimer:", later >= total
println"unknown timer:", debug.StopTimer("never started")
end
Output
true
both steps fit in the total: true
a timer keeps running after StopTimer: true
unknown timer: 0
Times differ from run to run and from machine to machine, so the example only prints comparisons. In your own program print the numbers themselves, for instance with log at the debug level. Measure a part several times, or over many iterations, before deciding it is slow; the first run often includes one time costs.
Assertions guard your own promises
Assert is for conditions that must hold if the code is correct, such as a balance that never goes below zero after a checked withdrawal. It is not for bad input from users or files: those are expected, and the program should answer them with an error value, as withdraw does with false when the balance is too small.
When an assertion fails, the program prints the message to standard error and stops at once with abort, so the exit status is 134 on Linux and no deferred code runs. With the first assertion broken, the run ends like this:
assertion failed: withdraw needs a positive amount
Aborted (core dumped)
Under a debugger (salam debug file.salam) the abort stops in the failing function, so you can look at its variables. Break stops there on purpose, without a failed condition. Do not leave it in code that runs without a debugger: with nothing attached, the program is stopped by the signal.
Find a leak with MemStats
MemStats returns one line with the number of allocations and frees, the bytes still in use (live) and the most that was ever in use (peak). The counting is compiled in only when you ask for it, so build or run with -DSALAM_MEM_DEBUG (or --asan). Print the line before and after a piece of work that should leave nothing behind: if live keeps growing every time it runs, that work leaks.
debug-memstats.salam
import debug
funcaverage_score(n: int, free_it: bool): int:
mut scores := Vector {} asVector<int>
repeat n in i:
scores.Push(60 + i % 40)
endmut total := 0each s in scores: total += s endif free_it: scores.Free() endret total / n
endfuncmain:
println"start: ", debug.MemStats()
repeat100in _:
average_score(500, true)
endprintln"freed: ", debug.MemStats()
repeat100in _:
average_score(500, false)
endprintln"leaked:", debug.MemStats()
end
The example is not run on this page because it needs the flag. With salam run -DSALAM_MEM_DEBUG leak.salam it prints:
After the first loop live is back near where it started; after the second it has grown by about 2 KB per call, the 500 numbers each forgotten vector held. salam memcheck file.salam goes further and runs the program under AddressSanitizer, which reports where each leaked block was allocated.
If the condition is false, prints assertion failed: and the message to standard error and stops the program with abort. It also runs in release builds.
debug-Enter.salam
import debug
funcchild():
debug.Enter("child")
println debug.Depth()
println debug.Stack()
debug.Exit()
endfuncmain:
debug.Enter("root")
child()
debug.Exit()
println debug.Depth()
debug.Assert(1 + 1 == 2, "the arithmetic holds")
debug.AssertNotNil(debug.MemStats() asvoid*, "the memory statistics")
debug.EnableTrace(true)
println debug.TraceEnabled()
debug.Trace("a trace message")
debug.StartTimer("loop")
mut total := 0repeat1000in i:
total += i
endprintln total, debug.StopTimer("loop") >= 0.0if total < 0:
debug.Break()
endend
One line with allocs, frees, live and peak bytes. Only in a build with -DSALAM_MEM_DEBUG or --asan; otherwise a line saying the numbers are unavailable.
The example for this item is shown with the ones above: debug-Enter.salam