The built-in debug module lets a program look at the machinery that runs the interpreter.

Where the other modules offer functionality and utilities to a program, this one offers a view of it; what a function is made of, how large it is, where in the source it was first written. Like any standard module, it is brought in with import:

import debug

It is a module for tools rather than for applications; a profiler, a coverage checker, a disassembler, or a program that wants to inspect itself. Most scripts will never need it.

It is also the most likely to grow and expand, of the standard modules, and, in its current form, it is dedicated to a single kind of value: functions.

What It Reveals, and What It Does Not

Before the functions themselves, it is worth being clear about the scope of the module.

It specifically exposes the prototype of a function, which is the compiled form of its code, as it was produced by the parser and before anything has run. A prototype describes the function as written; its name, its parameters, its constants, its bytecode, the lines that it spans. Everything in the module is a read-only look at that description.

It is not, however, a window into the running interpreter.

It does not give access to the stack, to the garbage collector, to the registry that C code uses to stores its private state, to the internal tables of the interpreter, or to the values of the variables of a function that is running.

These parts belong to the implementation, and the language deliberately keeps them out of reach of scripts, so that a program cannot damage the interpreter, and so that the interpreter is free to change how they work. Part III describes the tools available to C code, which owns the interpreter, and which can see far more than a script can.

The functions of the module only work with functions written in Teascript.

A function written in C has no prototype to begin with, and passing one is an error.

Describing a Function

The function debug.funcinfo takes a function and returns a map with a summary of its description:

function area(width, height)
{
    return width * height
}

var info = debug.funcinfo(area)
print(info["name"])         // area
print(info["params"])       // 2
print(info["isvararg"])     // false

These are the fields of the returned map:

FieldMeaning
nameThe name of the function
linedefinedThe line of the source where the function begins
lastlinedefinedThe line where it ends
paramsThe number of parameters
optparamsThe number of parameters with a default value
isvarargWhether the function takes a variable number of arguments
upvaluesThe number of variables it captures from the enclosing functions
childrenWhether it contains other functions inside of it
bytecodesThe number of bytecode instructions it has
kconstsThe number of constants it stores
stackslotsThe number of stack slots that it needs while running
currentlineThe line of the source for a given position, or -1
protoThe prototype itself, as a value

Some of them are of use to everybody.

The lines, the parameters, the name and the number of upvalues describe the function as the programmer sees it. The others, such as stackslots and kconsts, describe how the compiler built it, and are mostly of interest to those who work on the compiler or study how code is generated.

The number of upvalues tells how many outside variables a function holds on to, in the sense of closures, and it is zero for a function that depends only on its local parameters and variables:

function make_counter()
{
    var count = 0
    return () => {
        count += 1
        return count
    }
}

var counter = make_counter()
print(debug.funcinfo(counter)["upvalues"])      // 1

The function accepts an optional second argument, a position in the bytecode, which only affects the fields currentline. It is explained below. Without it, the position is the first instruction.

Inside a Function

When a function is first compiled, its code becomes a sequence of numbered instruction, and the values that the code mentions, such as the strings that it uses, are collected into a table of constants.

The remaining functions of the module read these parts, one item at a time. They all take a function prototype and an index, and they return nil when index is outside of what the function has, instead of raising an error. The first of the two, debug.funcbc, returns an instruction:

var info = debug.funcinfo(area)

for var pc in 0..info["bytecodes"]
{
    print(pc, debug.funcbc(area, pc))
}

Each instruction is just a number, that packs an operation and its operands, in a format that is private to the interpreter, and that is meant to be decoded by a program that knows it.

By itself is is of little use to read, but, together with the interpreter’s own bytecode listing option, it is the basis for any tool that analyzes code. The count of the instructions, from the field bytecodes, tells where the loop must stop.

The function debug.funck returns a constant by its index, with info["kconst"] telling how many there are:

function greet()
{
    print("Hello, Teascript!")
}

print(debug.funck(greet, 0))    // a constant used by the function, a string for example

And debug.funcuv describes one of the upvalues of a function, again as a number that tells how the variable is captured.

Lines

The most approachable of these functions is debug.funcline.

It takes a function and the position of an instruction, and returns the line of the source that the instruction came from. It is what makes it possible to say that a part of the compiled code corresponds to a part of the program:

print(debug.funcline(area, 0))

The same information is what the field currentline of debug.funcinfo provides, when the position is given as its second argument; for a position inside the function, the lines; for anything else, -1.

Several instructions usually belong to the same line, and a line that holds only a brace or a comment may belong to none, since it produces no code at all. So, going through all the instructions of a function, and looking at their lines, gives the lines of the program where something really happens. The example of this chapter does that.

An Example

The following program is a very small inspector.

The function report summarizes the shape of a function in a line, which uses the descriptions of the function, and the function code_lines goes through its instructions to find the lines of the source that contain code.

The second one is the principle behind a coverage tool, which needs to know which lines could run in order to tell which ones did not.

// inspect.tea
import debug

function area(w, h)
{
    return w * h
}

function sum(...values)
{
    var total = 0
    for var v in values
    {
        total += v
    }
    return total
}

function make_counter()
{
    var count = 0
    return () => {
        count += 1
        return count
    }
}

function report(label, f)
{
    var info = debug.funcinfo(f)
    var kind = info["isvararg"] ? "variadic" : "${info["params"]} parameters"
    print("${label}: ${kind}, ${info["upvalues"]} upvalues")
}

function code_lines(f)
{
    var seen = {}
    for var pc in 0..debug.funcinfo(f)["bytecodes"]
    {
        seen[debug.funcline(f, pc)] = true
    }
    return seen.keys.sort((a, b) => a < b)
}

report("area", area)
report("sum", sum)
report("counter", make_counter())

print("sum has code on lines " + code_lines(sum).join(", "))
$ tea inspect.tea
area: 2 parameters, 0 upvalues
sum: variadic, 0 upvalues
counter: 0 parameters, 1 upvalues
sum has code on lines 11, 12, 14, 16, 17

The lines with only a brace, or the blank ones, do not appear in the last result, since nothing was compiled for them. The map seen is used as a set, with the lines as its keys, because several instructions share each line, and the keys are sorted at the end, as a map keeps no order of its own.

This sort of program is the reason that the module exists. The rest of it is rarely needed, but when it is, there is no other way to see it.

With this we have reached the end of the tour of the standard library.

If you are looking for the details of any function, the Teascript API reference lists each of them with its exact signature.